考虑我在下拉列表中有以下值(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"
}
}
}
]
碰巧,你的selectedDropDownValues
字符串"Customer.Address.AddressLine1"
是JSONPath语法,所以你可以将你的Customer
对象转换为中间JObject
然后使用JsonExtensions.RemoveAllExcept(this JObject obj, IEnumerable<string> paths)
从this answer到How 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"
}
}
}
]