2

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?

4
  • 1
    Your json string is a list. You cannot deserialize it like that. What does your CustomType class look like? Commented Nov 30, 2016 at 7:27
  • Just use foreach(var item in CustomTypeList){ //here get item } Commented Nov 30, 2016 at 7:28
  • Actually, I don't want to create a new class to map the json keys. I just want to loop the array to get the key and value in each object. Commented Nov 30, 2016 at 7:30
  • 1
    It seems like you want a dictionary, but your json should be different for that. Dictionary json would look like this: {"key1":"value1", "key2":"value2"}Then you would deserialize it like JsonConvert.DeserializeObject<Dictionary<string, string>(str); Is this what you are looking for? Commented Nov 30, 2016 at 7:36

2 Answers 2

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

        }
Sign up to request clarification or add additional context in comments.

1 Comment

it should have more properties, what's the type of item.children<JProperty>()? JEnumerable<Jproperty>? Sorry I am new to C#. update question.
1

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

1 Comment

Thanks for you time to answer, the two solution both looks good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.