Garry Garry - 1 year ago 75
C# Question

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


I have a string str like below:

"key1": "value1",
"key2": "value2"
"key1": "value3",
"key2": "value4"

I know I could deserialize it to json like


Now I have a requirement to loop these objects and get the values. How should I do?

Answer Source
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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download