简体   繁体   中英

Query JSON Nested Object using LINQ

I have the below JSON where I'm trying to query the average confidence value and count of shape objects. I am using Newtonsoft to create the Json Object and to parse the Json Object. I'm gettiing error as "Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken". I understand I am treating object as array and hence the error, but I don't know how to treat the nested object. Please help.

    {
       "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);
            }
        }

Once you have JObject parsed, you can get requested result like this:

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()
};

You can easily query with direct LINQ keywords like this

considering this JSON

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

let's put it in a variable called json like this,

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

you can select all ids from the items where name is "one" using the following LINQ query

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

Then, you will have the result in an IEnumerable list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM