将类+子类转换为JSON格式的快速方法? [英] Fast way of converting a class + child classes into JSON format?

查看:282
本文介绍了将类+子类转换为JSON格式的快速方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我们称它为Person,它包含有关一个人的许多详细信息,并具有表示这些详细信息的许多属性和子类.

I have a class, let's call it Person, which holds a number of details about a person, and has number of properties and child classes that represent these details.

例如:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
    public Address HomeAddress { get; set; }
}

public class Address
{
    public string StreetName { get; set;}
    public string Town { get; set;}
    public string City { get; set;}
    public string Postcode { get; set;}
}

我需要将此数据转换为预定的固定结构的JSON文件.该文件的格式如下:

I need to transform this data into a JSON file of a pre-determined and fixed structure. The format of this file is as follows:

{
  "People": [
    {
      "PersonId": "1",
      "PersonFields": [
        {
          "Description": "string",
          "Value": "string"
        }
      ]
    }
  ]
}

上面的JSON文件包含一个数组,该数组的元素是使用Person对象中包含的详细信息填充的,每个人都有一个ID,然后每个人的详细信息(例如FirstNameLastNamePhoneNumberStreetNameTownCityPostcode都作为单独的元素存储在PersonFields数组中,其中Description是属性名称,而Value是该属性内保存的值.

The JSON file above holds an array, the elements of which are populated using the details held within a Person object, each person has an Id, and then the details of each e.g. FirstName, LastName, PhoneNumber, StreetName, Town, City and Postcode are all stored as separate elements within the PersonFields array, where the Description is the property name, and the Value is the value held inside that property.

因此本质上我需要能够将Person对象转换为以下内容:

So essentially I need to be able to convert the Person object into the below:

{
  "People": [
    {
      "PersonId": "1",
      "PersonFields": [
        {
          "Description": "FirstName",
          "Value": "John"
        },
        {
          "Description": "LastName",
          "Value": "Smith"
        },
        {
          "Description": "PhoneNumber",
          "Value": "0123456789"
        },
        {
          "Description": "StreetName",
          "Value": "Street"
        },
        {
          "Description": "Town",
          "Value": "Town"
        },
        {
          "Description": "City",
          "Value": "City"
        },
        {
          "Description": "Postcode",
          "Value": "AB1 2CD"
        },
      ]
    }
  ]
}

我显然可以手动执行此操作,实例化每个PersonFields元素并设置描述和值,然后使用它们填充数组.但是,这似乎是解决问题的漫长而不必要的方法.我想象有一种更快,更编程的方式来实现我的最终JSON文件,但是我不确定这是什么.

I can obviously do this manually, instantiating each PersonFields element and setting the description and value, then populating the array with them. However this seems like a very long winded and unnecessary way to go about this problem. I imagine there is a much faster and more programmatic way of achieving my final JSON file, but I'm unsure as to what that is.

推荐答案

首先将根类和属性类的所有属性放在一个列表中.每个列表项都是一个匿名类,其属性为字段Property,父属性为Parent;如果Property来自根类,则为null,即,对于Person中的所有属性,Parent为null ,对于Address中的所有属性,父级为HomeAddress.

First put all properties from the root class and the property classes in a single list. Each list item is an anonymous class with a field Property for the property and Parent for the parent property or null if Property is from the root class, i.e. for all properties from Person the Parent is null, for all properties from Address the parent is HomeAddress.

var rootProps = typeof(Person).GetProperties();
var flattenedProperties = new[] { new { Parent = (PropertyInfo)null, Properties = rootProps.Where(p => p.PropertyType == typeof(string)).ToArray() } }
    .Concat(rootProps.Where(p => p.PropertyType != typeof(string) && p.PropertyType.IsClass).Select(p => new { Parent = p, Properties = p.PropertyType.GetProperties() } ))
    .SelectMany(x => x.Properties, (x, p) => new { x.Parent, Property = p })
    .ToArray();

遍历每个人,读取所有属性值,构造具有预期输出结构的匿名对象树,然后将其输入JSON.NET. 我假设persons是您的Person对象的列表.

Iterate through each person, read all property values, construct an anonymous object tree of the expected output structure and then feed this into JSON.NET. I am assuming persons is a list of your Person objects.

var json = JsonConvert.SerializeObject(new
{
  People = persons.Select((x, i) => new
  {
    PersonId = (i + 1).ToString(),
    PersonFields = flattenedProperties.Select(p => new
    {
      Description = p.Property.Name,
      Value = p.Property.GetValue(p.Parent == null ? x : p.Parent.GetValue(x))
    })
  })
});

这篇关于将类+子类转换为JSON格式的快速方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆