简体   繁体   中英

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

Description:

I have a string str like below:

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

I know I could deserialize it to json like

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.

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

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

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