aman
aman

Reputation: 6262

Correctly iterating through json array

I am trying to parse through an json array and get the values from it but facing some issues.

I have my json that I get as:

[{
    "ID1":"1",
    "ID2":"2",
    "ID3":"3",
    "ID4":"4"
},
{
    "ID1":"5",
    "ID2":"6",
    "ID3":"7",
    "ID4":"8"
}]

The key ID1, ID2 etc are not fixed. For ex I can also have my json as:

[{
    "ID1":"1",
    "ID2":"2"
},
{
    "ID1":"5",
    "ID2":"6"
}]

Or there can be more keys also, ie its dynamic so I cant create a model and map my json to it.

I was trying to deserialize that and get the data by using the following code.:

public IActionResult GetData(string data)
{
    //here data is my json
    List<string> myList = JsonConvert.DeserializeObject<List<string>>(data);
    foreach (string s in myList)
    {
        //get values here
    }
    return Json("");
}

But above gives me error when deserializing as:

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while >parsing value: {. Path '', line 1, position 2.'

So I wanted to know how what is the correct method to loop through this json and get key values from it.

Upvotes: -1

Views: 67

Answers (1)

maccettura
maccettura

Reputation: 10819

Your JSON is a list of object, your issue is that you are trying to deserialize into a list of string. This will not work for obvious reasons.

Instead you want to deserialize into a list of objects, and since your objects keys change the best thing you can use is a Dictionary<string, string>:

var myList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data);

Keep in mind that the JSON you posted is a Dictionary<string, string> but as soon as you get integers or bools in that JSON you should change to Dictionary<string, object>

Fiddle here

Upvotes: 1

Related Questions