C#通过多个级别的数组仅基于键名称查找JSON值 [英] C# find JSON value based only on Key name through multiple levels of array

查看:70
本文介绍了C#通过多个级别的数组仅基于键名称查找JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有各种输入JSON格式的数据,所有数据都包含特定的键名 terminalSize .这是我所知道的唯一一块.JSON树的总数或JSON树中 terminalSize 的确切深度将永远是未知的,并且随时可能更改.

I have a variety of input JSON formatted data which all contain a particular key-name terminalSize. This is the only piece I know. The total number of JSON trees or the exact depth of terminalSize inside the JSON tree will forever be an unknown and subject to change.

我正在寻找一种C#解决方案来遍历JSON字符串的每个子级,并找到 terminalSize 然后获取值.

I'm looking for a C# solution to loop through every child of the JSON string and find terminalSize then fetch the value.

我已经成功尝试过此操作,但是只有在 terminalSize 在JSON的第一级中时,它才会起作用:

I've tried this with success but it will only work if terminalSize is in the first level of the JSON:

var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonString);
var dict = list.SelectMany(d => d).ToDictionary(p => p.Key, p => p.Value);
var terminal = dict["terminalSize"];

示例1.

{
  "status": "success",
  "data": {
    "terminalSize": 3766505.46,
    "totalTerminalSize": 3766505.46
  },
  "message": null
}

示例2.

{
  "lastUpdated": 1588020678,
  "terminalData": {
    "terminalSize": "451679852",
    "totalTerminalSize": "2100000000"
  },
  "terminalValueSeries": {
    "8x7": 2.33,
    "8x6": 3.73,
    "8x5": 4.49,
    "8x4": 3.68,
    "8x3": 13998,
    "8x2": 274936,
    "8x1": 5.09
  }
}

示例3.

{
  "terminalSize": "492612346.17",
  "terminalStatus": "online"
}

推荐答案

您还可以使用linq并根据 JProperty.Name 过滤 JProperty 集合.例如

You could also use linq and filter the JProperty collection based on JProperty.Name. For example

var result = JObject.Parse(jsonString)
                    .DescendantsAndSelf()
                    .OfType<JProperty>()
                    .Single(x=>x.Name.Equals("terminalSize"))
                    .Value;

这篇关于C#通过多个级别的数组仅基于键名称查找JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆