Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JObject how to read values in the array?

Tags:

c#

json.net

People also ask

How do you access JObject values?

The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.

How do you iterate through JObject?

If you look at the documentation for JObject , you will see that it implements IEnumerable<KeyValuePair<string, JToken>> . So, you can iterate over it simply using a foreach : foreach (var x in obj) { string name = x.

How do I convert JArray to JObject?

it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.

What is the difference between JToken and JObject?

So you see, a JObject is a JContainer , which is a JToken . Here's the basic rule of thumb: If you know you have an object (denoted by curly braces { and } in JSON), use JObject. If you know you have an array or list (denoted by square brackets [ and ] ), use JArray.


JObject uploadData = JObject.Parse(json);
int rowsAdded = Convert.ToInt32((string)uploadData["d"][0]["numberOfRowsAdded"])

You need to cast to JArray:

string json = "{\"d\":[{\"numberOfRowsAdded\":\"26723\"}]}";
JObject parsed = JObject.Parse(json);
JArray array = (JArray) parsed["d"];
Console.WriteLine(array.Count);

You can cast your JObject as a dynamic object.
You can also cast your array to JArray object.

JObject yourObject;
//To access to the properties in "dot" notation use a dynamic object
dynamic obj = yourObject;
//Loop over the array
foreach (dynamic item in obj.d) {
  var rows = (int)item.numberOfRowsAdded;
}

I played around with writing a generic method that can read any part of my json string. I tried a lot of the answers on this thread and it did not suit my need. So this is what I came up with. I use the following method in my service layer to read my configuration properties from the json string.

public T getValue<T>(string json,string jsonPropertyName)
{                      
    var parsedResult= JObject.Parse(json);

    return parsedResult.SelectToken(jsonPropertyName).ToObject<T>();
}

and this is how you would use it :

var result = service.getValue<List<string>>(json, "propertyName");

So you can use this to get specific properties within your json string and cast it to whatever you need it to be.