简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM