【问题标题】:How to count the length of value array in JSON如何计算数组json中的值
【发布时间】:2021-12-03 12:18:39
【问题描述】:

我在下面有一个 JSON 代码:

{
  "value": [
    {
      "name": "504896c031d2fcb9",
      "location": "North Europe",
      "properties": {
        "state": "UNKNOWN",
        "name": "504896c031d2fcb9",
        "siteInstanceName": "504896c031d2fcb93ec",
        "healthCheckUrl": null,
        "machineName": "lw0s",
        "containers": null
      }
    },
    {
      "name": "35aafa",
      "location": "North Europe",
      "properties": {
        "state": "UNKNOWN",
        "name": "35aafae",
        "siteInstanceName": "35aafaeff",
        "healthCheckUrl": null,
        "machineName": "lw1s",
        "containers": null
      }
    }
  ],
  "nextLink": null,
  "id": null
}

我已将 JSON 转换为如下所述的动态:

string kq = reader.ReadToEnd();
dynamic jss = JsonConvert.DeserializeObject(kq);

我想知道如何计算c#中有多少个值?上面的例子有2个值

谢谢。

【问题讨论】:

  • 为什么要反序列化为dynamic 而不是命名类?无论如何,您可以使用jss.value.Length
  • 一个命名类需要时间来写:(
  • 如果您可以在几个月后摸不着头脑,因为您不记得自己的数据结构是什么样子,只是因为您懒得花几秒钟时间从中提取一个类给定数据...这是你的程序。
  • 同意@HimBromBeere - 在 C# 中开发时,我想不出很多次我不得不使用动态。动态类型有它的位置,但这不是它

标签: c# json


【解决方案1】:

如果你知道钥匙,你可以做类似的事情

 dynamic jss = JsonConvert.DeserializeObject(kq);
 jss["value"].Count

【讨论】:

  • 感谢您的建议
【解决方案2】:

转换为JArray.Count

也许,如果value 不是数组类型,则转换后的array 将返回为null

您可以添加处理来检查是否不是null并获取.Count

dynamic jss = JsonConvert.DeserializeObject(kq);
JArray array = jss["value"] as JArray;
Console.WriteLine(array != null ? array.Count : 0);

Sample program (JsonConvert.DeserializeObject)


建议:

由于您将 JSON 字符串反序列化为 dynamic,因此使用 JsonConvert.DeserializeObject 它将返回 JObject 类型的值。

我建议使用JObject.Parse 而不是JsonConvert.DeserializeObject<T>(专为转换为强类型对象而设计)。

您可以阅读这个问题:JObject.Parse vs JsonConvert.DeserializeObject 了解更多信息。

using Newtonsoft.Json.Linq;

JObject jss = JObject.Parse(json);
JArray array = jss["value"] as JArray;
Console.WriteLine(array != null ? array.Count : 0);

Sample program (JObject.Parse)

【讨论】:

  • 谢谢。我会试试的
猜你喜欢
  • 2020-04-05
  • 1970-01-01
  • 2016-03-20
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
  • 2014-09-16
相关资源
最近更新 更多