简体   繁体   English

使用Json.net [C#]循环json数组中的对象

[英]Loop objects in a json array by using Json.net [C#]

Description: 描述:

I have a string str like below: 我有一个字符串str如下:

[
  {
    "key1": "value1",
    "key2": "value2"
  },
  {
    "key1": "value3",
    "key2": "value4"
  }
]

I know I could deserialize it to json like 我知道我可以将其反序列化为json

JsonConvert.DeserializeObject<CustomType>(str).

Now I have a requirement to loop these objects and get the values. 现在我需要循环这些对象并获取值。 How should I do? 我应该怎么做?

JArray array = JsonConvert.DeserializeObject<JArray>(json);

foreach(JObject item in array)
{
    var a = item.Children<JProperty>().FirstOrDefault().Name;
    var b = item.Children<JProperty>().FirstOrDefault().Value;

}

Here if you have only one property in every element of the array. 这里,如果您在数组的每个元素中只有一个属性。 If you have multiple properties you need to loop all the children. 如果您有多个属性,则需要循环所有子项。

Check dotNetFiddle for full code example. 检查dotNetFiddle以获取完整的代码示例。

EDIT 编辑

If you have more than one property per object your loop should look like this. 如果每个对象有多个属性,则循环应如下所示。

        foreach(JObject item in array)
        {
            foreach(var prop in item.Children<JProperty>())
            {
                Console.WriteLine(prop.Name + ": " + prop.Value);
            }
            //Console.WriteLine(item.Children<JProperty>().FirstOrDefault().Name + ": " + item.Children<JProperty>().FirstOrDefault().Value);

        }

You can deserialize your json string to a List<Dictionary<string, string>> 您可以将json字符串反序列化为List<Dictionary<string, string>>

List<Dictionary<string, string>> list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(str);

Then loop this list 然后循环此列表

List<string> values = new List<string>();
foreach(Dictionary<string, string> dict in list)
{
    foreach(KeyValuePair<string, string> kvPair in dict)
    {
        values.Add(kvPair.Value);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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