如何从具有特定属性的对象的C#列表中创建json字符串?

时间:2018-09-01 11:17:38

标签: c# json list c#-3.0

考虑到我在下拉列表(dropDownList变量中具有以下值,并且用户选择的值在selectedDropDownValues列表中。

DB api返回客户列表(customerDBList变量)。

现在的要求是从选定的值构建JSON,如下所述-

var dropDownList = new[] { "Customer.Id", "Customer.FirstName", "Customer.LastName", "Customer.Address.AddressLine1", "Customer.Address.AddressLine2" };

var selectedDropDownValues = new[] { "Customer.Id", "Customer.FirstName", "Customer.Address.AddressLine1" };

var customerDBList = new List<Customer>(){
                new Customer {
                    Id=1,
                    FirstName="John",
                    LastName="Desouza",
                    Address=new Address{            
                                AddressLine1="1 Street",
                                AddressLine2="Linking Road"
                    }},        
                new Customer {
                    Id=2,
                    FirstName="Sam",
                    LastName="Lewis",
                    Address=new Address{            
                                AddressLine1="Fedral Highway",
                                AddressLine2="Louisville"
                    }                
                }};

预期JSON输出为-

[
  {
    "Customer": {
      "Id": 1,
      "FirstName": "John",
      "Address": {
        "AddressLine1": "1 Street"
      }
    }
  },
  {
    "Customer": {
      "Id": 2,
      "FirstName": "Sam",
      "Address": {
        "AddressLine1": "Fedral Highway"
      }
    }
  }
]

1 个答案:

答案 0 :(得分:1)

碰巧,您的selectedDropDownValues字符串"Customer.Address.AddressLine1"采用JSONPath语法,因此您可以将Customer对象转换为中间JObject,然后将其修剪掉从this answer到{em> How to perform partial object serialization providing "paths" using Newtonsoft JSON.NET 使用JsonExtensions.RemoveAllExcept(this JObject obj, IEnumerable<string> paths)的值。

请注意,您所需的JSON具有数据模型中不存在的{ "Customer": { ... } }嵌套级别,因此在过滤之前需要手动插入它:

var rootName = "Customer";

var query = customerDBList
    // Convert to JObject
    .Select(c => JObject.FromObject(c))
    // Add additional level of object nesting { "Customer": { ... } } 
    .Select(o => new JObject( new JProperty(rootName, o)))
    // Remove all but selected properties.
    .Select(o => o.RemoveAllExcept(selectedDropDownValues));

var json = JsonConvert.SerializeObject(query, Formatting.Indented);

工作示例.Net小提琴here,根据需要显示生成的JSON

[
  {
    "Customer": {
      "Id": 1,
      "FirstName": "John",
      "Address": {
        "AddressLine1": "1 Street"
      }
    }
  },
  {
    "Customer": {
      "Id": 2,
      "FirstName": "Sam",
      "Address": {
        "AddressLine1": "Fedral Highway"
      }
    }
  }
]