Garry Garry - 6 days ago 6
C# Question

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?

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

        }