Bora
Bora

Reputation: 127

How to get children data from json via linq

I'm using json.net and i've a json data like that,

[
{
  "ID":1098,
  "Name":"JC",
  "Issues":[
     {
        "PriorityLevel":"Low",
        "State":"Open"
     },
     {
        "PriorityLevel":"Low",
        "State":"Open"
     }
  ]
}
]    

I just want to get childeren data from Issues via linq. I can reach parent but cannot children. If i reach children data directly i don't need to put more than one for loop.

Thank you.

Upvotes: 4

Views: 4822

Answers (2)

jsmith
jsmith

Reputation: 7278

You can just create a Json Object and extract the properties into an Anonymouse type that you can then query with Linq.

string response = @"[{
  ""ID"":1098,
  ""Name"":""JC"",
  ""Issues"":[
     {
        ""PriorityLevel"":""Low"",
        ""State"":""Open""
     },
     {
        ""PriorityLevel"":""Low"",
        ""State"":""Open""
     }
  ]}]";

var jsonObject = JObject.Parse(response);
var issues = jsonObject["Issues"].Select(x => new
             {
                 PriorityLevel = (string)x.SelectToken("PriorityLevel"),
                 State = (string)x.SelectToken("State")
             });

You use SelectToken to grab the children of Issues. Now you can query issues for whatever you want.

var lowPriorities = issues.Where(x => x.PriorityLevel == "Low");

Here is a direct link to the json.net page on "Deserializing Using LINQ Example".

Upvotes: 4

mcintyre321
mcintyre321

Reputation: 13306

Here you go

{
    var json = @"[      {
    ""ID"":1098,
    ""Name"":""JC"",
    ""Issues"":[
        {
            ""PriorityLevel"":""Low"",
            ""State"":""Open""
        },
        {
            ""PriorityLevel"":""Low"",
            ""State"":""Open""
        }
    ]}]";

    var a = JArray.Parse(json);

    var issues = a.SelectMany (x => x["Issues"]);
    var lowPriorities = issues.Where(x => ((string) x["PriorityLevel"]) == "Low");
}

Upvotes: 2

Related Questions