1

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);
            }
        }
4
  • What does not work for you? Commented May 11, 2020 at 8:19
  • What you tried so far? Can you change this json document? I can see common properties in all shapes, if this is true then shapes will be array of object . This will make your life easy to calculate average Commented May 11, 2020 at 8:20
  • Deserialize the part you need into a List<Shapes> then use linq Average(x => x.SomeProperty). Commented May 11, 2020 at 9:03
  • May we have the "I am using Newtonsoft to [...] parse the Json Object." part? What error do you have? minimal reproducible example Commented May 11, 2020 at 9:07

2 Answers 2

1

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()
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.