【问题标题】:Query JSON Nested Object using LINQ使用 LINQ 查询 JSON 嵌套对象
【发布时间】:2020-05-11 08:13:01
【问题描述】:

我有以下 JSON,我试图在其中查询平均 confidence 值和 shape 对象的计数。我正在使用 Newtonsoft 创建 Json 对象并解析 Json 对象。我遇到错误“无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken”。我知道我将对象视为数组,因此会出现错误,但我不知道如何处理嵌套对象。请帮忙。

    {
       "channel":{
          "description": "James Newton-King\"s blog.",
          "region":[
             {
            "title": "Json.NET 1.3 + New license + Now on CodePlex",
            "description": "Announcing the release of Json.NET 1.3",
            "link": "http://james.newtonking.com/projects/json-net.aspx",
            "shape":{
               "square":{
                  "type":"number",
                  "text":"$81.22",
                  "confidence":0.983
                    },
               "circle":{
                  "type":"string",
                  "valueString":"50741890",
                  "text":"50741890",
                  "confidence":1.0
                    },
               "rectangle":{
                  "type":"date",
                  "text":"01/01/2020",
                  "confidence":1.0
                    }
                }
             }
          ],
          "errors":[
          ]
       }
    }

//My code
    public void qryNode()
        {
            string json = File.ReadAllText(@"C:\Extract.json");
            JObject rss = JObject.Parse(json);
            var categories =
                from c in rss["channel"]["region"].SelectMany(i => i["shape"]).Values<string>()
                group c by c
                into g
                orderby g.Count() descending
                select new { Category = g.Key, Count = g.Count() };

            foreach (var c in categories)
            {
                Console.WriteLine(c.Category + " - Count: " + c.Count);
            }
        }

【问题讨论】:

  • 什么不适合你?
  • 到目前为止您尝试了什么?你能改变这个json文件吗?我可以看到所有形状的共同属性,如果这是真的,那么 shapes 将是 object 数组。这将使您的生活易于计算平均值
  • Deserialize the part 你需要进入一个列表 然后use linq Average(x =&gt; x.SomeProperty)
  • 我们可以有“我正在使用 Newtonsoft [...] 解析 Json 对象。”部分吗?你有什么错误? minimal reproducible example

标签: c# json linq


【解决方案1】:

一旦你解析了 JObject,你可以得到如下请求的结果:

var jObject = JObject.Parse(json);

var shapes = jObject["channel"]["region"]
    .SelectMany(j => j["shape"]);

var confidences = shapes
    .SelectMany(s => s.Select(i => i["confidence"]
        .Value<float>()))
    .ToList();

var result = new
{
    ShapesCount = confidences.Count,
    AverageConfidence = confidences.Average()
};

【讨论】:

    【解决方案2】:

    您可以像这样使用直接 LINQ 关键字轻松查询

    考虑到这个 JSON

    {
        "items": [
            {
                "id": "10",
                "name": "one"
            },
            {
                "id": "12",
                "name": "two"
            }
        ]
    }
    

    让我们像这样把它放在一个名为json的变量中,

    JObject json = JObject.Parse("{'items':[{'id':'10','name':'one'},{'id':'12','name':'two'}]}");
    

    您可以使用以下 LINQ 查询从名称为 "one" 的项目中选择所有 ID

    var Ids =
        from item in json["items"]
        where (string)item["name"] == "one"
        select item["id"];
    

    然后,您将在 IEnumerable 列表中获得结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多