【问题标题】:Parsing Dynamic JSON解析动态 JSON
【发布时间】:2017-02-11 05:19:19
【问题描述】:

我收到一个 JSON 文件,其中包含一个文件列表,每个文件都有一个数字,代表它包含的总行数。文件名会随着时间而改变。 JSON.NET 是否提供了一种机制来处理这种情况?

在下面的示例 JSON 中,我对 noOfProductsByFile 下的项目特别感兴趣。文件列表是可变的,我需要通过某种类型的动态对象来使用它们。

{
  "noOfProductsByFileType" : {
    "rdi_product_stuff" : 41228,
    "rdi_product_junk" : 62519,
    "rdi_product_otherStuff" : 165023,
    "rdi_product_bobsJunk" : 1289
  },
  "startTime" : "20160907050000",
  "endTime" : "20160907052713",
  "timeTaken" : "27 minutes and 13 seconds",
  "noOfProductsBySecurityType" : {
    "AGENCIES" : 41228,
    "ASTBK" : 50991,
    "TSYCURV" : 78
  },
  "noOfProductsByFile" : {
    "rdi_product_stuff_1_of_1.json" : 41228,
    "rdi_product_junk_1_of_2.json" : 60219,
    "rdi_product_junk_2_of_2.json" : 2300,
    "rdi_product_myStuff_1_of_2.json" : 147690,
    "rdi_product_myStuff_2_of_2.json" : 17333,
    "rdi_product_test_1_of_1.json" : 1289
  },
  "noOfProducts" : 1925914
}

【问题讨论】:

  • 是的,因为您解析的是 json 文本而不是文件

标签: c# json json.net


【解决方案1】:

有几个选项可供使用。这是一个使用 ExpandObject

dynamic dynData = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, new ExpandoObjectConverter());

然后您可以像引用普通对象一样引用字段:

dynData.noOfProductsByFileType.rdi_product_stuff

如果您需要处理可能存在或不存在的字段,可以将 ExpandoObjects 强制转换为 IDictionary 并按如下方式引用字段:

((IDictionary<string,object>)dynData)["noOfProductsByFileType"]

分配给 IDictionary 类型并遍历属性或测试属性是否存在

var dictData = (IDictionary<string,object>)dynData;
var noOfProductsByFileTypeDict = (IDictionary<string,object>)dynData.noOfProductsByFileType; // objects within objects

属性测试

dictData.containsKey("testprop"); // test for a property - testprop

或迭代

foreach (KeyValuePair<string, int> pair in noOfProductsByFileTypeDict) ... //iterate

【讨论】:

  • 不错的答案! OP 可能想要迭代而不是硬编码这些文件的名称。这是一个动态列表。但我看到,使用ExpandoObject,您可以安全地使用foreach 覆盖dynData.noOfProductsByFile,然后读取.Key.Value 属性。你可能想修改你的答案。
  • FWIW:您实际上并不需要强制转换为字典进行迭代。你可以只做foreach (var property in dynData.noOfProductsByFile) 然后string file = property.Key;long noOfProducts = property.Value;
【解决方案2】:

是的。有很多方法可以处理这个问题。一种简单的方法是使用JObject

var jsonString = "...";
var jObject = JObject.Parse(jsonString);
foreach (JProperty e in jObject["noOfProductsByFile"])
{
    var file = e.Name;
    var noOfProducts = e.Value;
    Debug.WriteLine(file);
    Debug.WriteLine(noOfProducts);
}

【讨论】:

  • 你也可以使用 JObject.Parse(jsonstring) 代替 JsonConvert
  • 好收获。已更新。
猜你喜欢
  • 2019-12-27
  • 2013-12-20
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 2020-04-17
相关资源
最近更新 更多