来自数据表和IList的嵌套JSON

时间:2018-12-11 08:39:22

标签: c# json asp.net-mvc asp.net-mvc-4

我有两个变量

  

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"
          },
....
]

1 个答案:

答案 0 :(得分:0)

在数据表中,您有一个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;
    }
}