【问题标题】:Parsing a nested dictionary with arbitrary numerical keys and object array values使用任意数字键和对象数组值解析嵌套字典
【发布时间】:2018-05-15 07:18:38
【问题描述】:

给定 json 字符串

var testJson = @"{'entry1': {
                       '49208118': [
                          {
                             'description': 'just a description'
                          },
                          {
                             'description': 'another description' 
                          }
                       ],
                       '29439559': [
                          {
                             'description': 'just a description'
                          },
                          {
                             'description': 'another description' 
                          }
                       ]
                     }
                }";

49208118的数组值可以通过

var root = JToken.Parse(testJson);
var descriptions = root.SelectTokens("..49208118[*]").ToList();

根据this answer.

但是entry1下的整个子结构如何解析成字典

 Dictionary<string, JArray> descriptions;

将数字 ID 映射到 JObjects 的数组?

【问题讨论】:

  • 但是如果 Key 未知,你怎么知道要访问哪个元素?
  • 为了这个例子,我们可以用任意的动态数字键泛化为 n 个数字键值对。
  • 我想,我不是很明白你的问题,但是像var root = d.SelectToken("$..entry1");这样的东西不会给你这样的字典吗?

标签: c# json json.net


【解决方案1】:

因为问题是如何将 entry1 解析为 Dictionary&lt;string, JArray&gt; - 最简单的选择是:

JToken root = JToken.Parse(testJson);
Dictionary<string, JArray> descriptions = root["entry1"].ToObject<Dictionary<string, JArray>>();

Json.NET 允许在解析时混合 .NET 类 (Dictionary) 和他自己的类 (JArray) 而不会出现问题。

【讨论】:

    【解决方案2】:

    这个怎么样:

    string selector = String.Format("..{0}[*]", yourKey);
    var descriptions = root.SelectTokens(selector).ToList();
    

    【讨论】:

    • 什么是“yourKey”?请记住,事先不知道 id。唯一知道的是有一个带有数组值的任意数字键。
    • 您要检索扁平数组还是嵌套数组?
    • 后者:嵌套。即,字典 { id : descriptions}
    猜你喜欢
    • 2017-06-03
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    相关资源
    最近更新 更多