从数据表和 IList 嵌套 JSON

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;
    }
}