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

问题描述 投票:0回答:1

考虑我在下拉列表中有以下值(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"
      }
    }
  }
]
c# json list c#-3.0
1个回答
1
投票

碰巧,你的selectedDropDownValues字符串"Customer.Address.AddressLine1"JSONPath语法,所以你可以将你的Customer对象转换为中间JObject然后使用JsonExtensions.RemoveAllExcept(this JObject obj, IEnumerable<string> paths)this answerHow to perform partial object serialization providing "paths" using Newtonsoft JSON.NET修剪不需要的值。

请注意,您所需的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"
      }
    }
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.