Masinde Muliro
Masinde Muliro

Reputation: 1183

How to access children values of a JObject

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#?

Upvotes: 8

Views: 28240

Answers (2)

Janilson
Janilson

Reputation: 1193

First things first, that json is not properly formatted, it should be:

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

Now, getting to the answer, I believe this is what you want

var jObject = JObject.Parse(testJson);
var children = jObject.Children().Children();
var valuesList = new List<string>();
foreach (var child in children)
{
    valuesList.AddRange(child["values"].ToObject<List<string>>());
}
var valuesJsonArray = JsonConvert.SerializeObject(valuesList); // not sure if you want an array of strings or a json array of strings

Upvotes: 3

Dhiraj Sharma
Dhiraj Sharma

Reputation: 4879

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);

Upvotes: 14

Related Questions