Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a key exists in a NewtonSoft JObject C#

I am having a JSON object (NewtonSoft.JObject). It contains several entries in this format:

{
  "id": "b65ngx59-2c67-4f5b-9705-8525d65e1b8",
  "name": "TestSample",
  "versions": []
},
{
  "id": "8acd8343-617f-4354-9b29-87a251d2f3e7",
  "name": "template 2",
  "versions": [
    {
      "id": "556ng956-57e1-47d8-9801-9789d47th5a5",
      "template_id": "8acd8343-617f-4354-9b29-87a251d2f3e7",
      "active": 1,
      "name": "1.0",
      "subject": "<%subject%>",
      "updated_at": "2015-07-24 08:32:58"
    }
  ]
}

Note: Just an example.

I have written a code so that I get the ids in a list:

List<JToken> templateIdList = jObj.Descendants()
            .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id")
            .Select(p => ((JProperty)p).Value)
            .ToList();

Note: jObj is the JSON object

The output list is:

[0] - b65ngx59-2c67-4f5b-9705-8525d65e1b8
[1] - 8acd8343-617f-4354-9b29-87a251d2f3e7
[2] - 556ng956-57e1-47d8-9801-9789d47th5a5

It gives all the ids.Now I want to add a condition to the linq so that only the template_ids containing active with value = 1 in them should be populated in the list.

The required output:

[0] - 8acd8343-617f-4354-9b29-87a251d2f3e7

What changes should I make to the linq query to get this?

EDIT: The complete code is

public bool CheckIfTemplateExists(string template)
{
 bool exists = false;

 //web service call to retrieve jsonTemplates
 JObject jObj = JObject.Parse(jsonTemplates);

 List<JToken> templateIdList = jObj.Descendants()
                .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id")
                .Select(p => ((JProperty)p).Value)
                .ToList();

 if(templateIdList.IndexOf(template) != -1)
  {
   exists = true;
  }
return exists
}

The jsonTemplates in the above code is a string of the format:

{"templates": 
[{"id":"b65cae59-2c67-4f5b-9705-07465d65e1b8",
"name":"TestSample","versions":[]},
{"id":"8edb8343-617f-4354-9b29-87a251d2f3e7",
"name":"Template1",
"versions":[{"id":"556bb956-57e1-47d8-9801-9388d47cc5a5",
"template_id":"8edb8343-617f-4354-9b29-87a251d2f3e7",
"active":1,
"name":"1.0","subject":"\u003c%subject%\u003e",
"updated_at":"2015-07-24 08:32:58"}]}
like image 343
nitinvertigo Avatar asked Jul 30 '15 10:07

nitinvertigo


1 Answers

Try this one:

List<JToken> templateIdList = jObj["templates"].Children()
            .Where(child => child["versions"] != null 
               && child["versions"].Any(version => version["active"].Value<int>() == 1))
            .Select(x => x["id"]);
like image 199
Oleksandr Galperin Avatar answered Oct 12 '22 23:10

Oleksandr Galperin