Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a node (JObject) within JArray using JSON.NET library

Tags:

json

c#

json.net

I am using JSON.NET library. I have created few JObjects and added them to a JArray.

JArray array = new JArray();

JObject obj = new JObject();
obj.Add(new JProperty("text", "One"));
obj.Add(new JProperty("leaf", false));
array.Add(obj);

obj = new JObject();
obj.Add(new JProperty("text", "Two"));
obj.Add(new JProperty("leaf", false));
array.Add(obj);

obj = new JObject();
obj.Add(new JProperty("text", "Three"));
obj.Add(new JProperty("leaf", true));
array.Add(obj);

Now I want to find a JObject who's text (JProperty) is Two. How can I find a JObject within a JArray by using a JProperty.

like image 920
SharpCoder Avatar asked Nov 01 '13 11:11

SharpCoder


People also ask

What is JObject C#?

JObject. It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. It is presented in Newtonsoft.

What is JObject and JToken?

The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...

How do I add JProperty to JArray?

you can not add directly. JProperty subdatalist = new JProperty("MySubData",myarray); myobj. Add(subdata); // this is the correct way I suggest.

What is JArray C#?

JArray(Object[]) Initializes a new instance of the JArray class with the specified content. JArray(JArray) Initializes a new instance of the JArray class from another JArray object.


1 Answers

You can find it like this:

JObject jo = array.Children<JObject>()
    .FirstOrDefault(o => o["text"] != null && o["text"].ToString() == "Two");

This will find the first JObject in the JArray having a property named text with a value of Two. If no such JObject exists, then jo will be null.

like image 92
Brian Rogers Avatar answered Oct 26 '22 15:10

Brian Rogers