[英]Nested JSON from datatable and IList
我有兩個變量
Datatable listOfObject
產生如下的JSON
"listofObject" : [
{
"Obj1": "Some String Value",
"Obj2": "Some Date Value",
"Obj3": "Some Int Value",
"Obj4": "Some Date Value",
....
}
]
和另一個對象
IList<Class> ObjectInfo
產生如下的JSON
"ObjectInfo" : [
{
"name" : "Obj1",
"Style" : "Style Name",
"Data Type" : "String"
},
{
"name" : "Obj2",
"Style" : "Style Name",
"Data Type" : "Date"
},
{
"name" : "Obj3",
"Style" : "Style Name",
"Data Type" : "Int"
},
.....
]
我如何將它們組合成一個JSON結構,如下所示
"finalStructure" :[
"Obj1": {
"Style" : "Style Name",
"Data Type" : "String"
},
"Obj2": {
"Style" : "Style Name",
"Data Type" : "Date"
},
"Obj3": {
"Style" : "Style Name",
"Data Type" : "Int"
},
....
]
從數據表中,您有一個IEnumerable<IDictionary<string, string>>
,因此您要做的是首先創建一個查找,然后可以安全地投影結果:
var items = listOfObjects.FromJson<IEnumerable<IDictionary<string, string>>>();
var info = objectInfo.FromJson<IEnumerable<IDictionary<string, string>>>()
.ToLookup(it => it.Single(k => k.Key == "name").Value, it => it.Where(k => k.Key != "name"));
var restructured = items
.SelectMany(it => it.Keys)
.GroupBy(it => it)
.Select(it => new
{
Key = it.Key,
Value = info[it.Key].SelectMany(fo => fo).ToDictionary(fo => fo.Key, fo => fo.Value)
})
.ToDictionary(it => it.Key, it => it.Value);
// extension method with NewtonSoft.JSON.net
public static T FromJson<T>(this string json)
{
var serializer = new JsonSerializer();
using (var sr = new StringReader(json))
using (var jr = new JsonTextReader(sr))
{
var result = serializer.Deserialize<T>(jr);
return result;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.