如何访问JObject的子值

时间:2018-06-16 04:30:14

标签: c# json.net

我有一个看起来像这样的JObject项目:

{

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

如何在C#中将值作为单个字符串获取?

2 个答案:

答案 0 :(得分:1)

首先从字符串中创建JObject

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"];

将字符串的JArray转换为字符串数组

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

加入你的字符串数组&amp;创造一个单一的字符串

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

这里有完整的代码..

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

答案 1 :(得分:1)

首先,json格式不正确,应该是:

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

现在,得到答案,我相信这就是你想要的

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