I have this JSON:
{ "client_id": "26075235", "client_version": "1.0.0", "event": "app.uninstall", "timestamp": 1478741247, "data": { "user_id": "62581379", "site_id": "837771289247593785", "platform_app_id": "26075235" } }
I parse it into a JSON.NET JObject and I can successfully access the first level of values using e.g. (string)RequestBody.SelectToken("client_id")
How do I access the value of "user_id" using a JPath expression (or by accessing a child object of the JSON.NET JObject)? This doesn't work:
(string)RequestBody.SelectToken("data[0].user_id")
and I can't do this to parse the 'data' part of the JSON:
JObject RequestBodyData = JObject.Parse((string)RequestBody.SelectToken("data"));
as the compiler seems to recognise RequestBody.SelectToken("data")
as an object (I get the error 'Can not parse object into string')
and I don't want to parse the original JSON into a custom C# object as I'm developing a solution that needs to be able to generically parse JSON into a JObject (or any other type of generic object for handling JSON), so it can be parsed in a relatively consistent way.
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.
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.
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 ...
The method JObject. Parse() is a JObject class method. This parse method is used to parse a JSON string into a C# object. It parses the data of string based on its key value. This key value is then used to retrieve the data.
SelectToken("data[0].user_id")
doesn't work because there isn't an array in your JSON. You should use SelectToken("data.user_id")
instead.
Fiddle: https://dotnetfiddle.net/K0X4ht
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With