【问题标题】:Nested JSON from datatable and IList来自数据表和 IList 的嵌套 JSON
【发布时间】:2019-05-12 05:08:49
【问题描述】:

我有两个变量

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

【问题讨论】:

  • 你可以创建一个类来模拟包含来自两个实例的数据的预期结构,不幸的是,此时你没有展示你目前实现这一目标的尝试。
  • 在我看来你根本没有将它们结合起来;您的最终 JSON 结构仅包含来自 ObjectInfo 列表的数据。 DataTable 的值是否应该在某个地方?此外,您要求的最终结构是无效的 JSON;键值对不能直接出现在数组内部。你的意思是那些方括号[] 是花括号{}
  • @BrianRogers 是的,如果它们是花括号,我只能让它工作。 (不使用任何类)

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2018-10-26
    • 1970-01-01
    • 2020-09-07
    • 2018-10-30
    • 2015-08-26
    相关资源
    最近更新 更多