Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access children values of a JObject

Tags:

c#

json.net

I have a JObject item that looks like this:

{

        "part":
         {
             "values": ["engine","body","door"]
             "isDelivered": "true"
        },
        {
        "manufacturer":
         {
             "values": ["Mercedes"]
             "isDelivered": "false" 
         }
}

How can I get the values as a single string in C#?

like image 323
Masinde Muliro Avatar asked Jun 16 '18 04:06

Masinde Muliro


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 I know if JObject is empty or null?

To check whether a property exists on a JObject , you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

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 ...

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. Json.


1 Answers

First create JObject from your string

String json = "{\"part\":{ \"values\": [\"engine\",\"body\",\"door\"], \"isDelivered\": \"true\"},\"manufacturer\":{\"values\": [\"Mercedes\"],\"isDelivered\": \"false\"}}";
JObject jObject = JObject.Parse(json);

Then get values array (from part for example as)

JArray jArray= (JArray)jObject["part"]["values"];

Convert JArray of String to string array

string[] valuesArray = jArray.ToObject<string[]>();

Join your string array & create a singe string

String values = string.Join(",",valuesArray);

Full code here ..

String json = "{\"part\":{ \"values\": [\"engine\",\"body\",\"door\"], \"isDelivered\": \"true\"},\"manufacturer\":{\"values\": [\"Mercedes\"],\"isDelivered\": \"false\"}}";
JObject jObject = JObject.Parse(json);
JArray jArray= (JArray)jObject["part"]["values"];
string[] valuesArray = jArray.ToObject<string[]>();
String values = string.Join(",",valuesArray);
Console.WriteLine(values);
like image 138
Dhiraj Sharma Avatar answered Oct 02 '22 00:10

Dhiraj Sharma