代码之家  ›  专栏  ›  技术社区  ›  Zerotoinfinity HLGEM

来自datatable和IList的嵌套JSON

  •  2
  • Zerotoinfinity HLGEM  · 技术社区  · 7 年前

    我有两个变量

    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 回复  |  直到 7 年前
        1
  •  0
  •   reckface    7 年前

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