-1

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.

3
  • 4
    You dont have a list of string, you have a list of object. Since your keys are not fixes you can just use a Dictionary<string, string> as your object Commented Mar 29, 2018 at 14:36
  • @maccettura I tried to use this: Dictionary<string, string> conditionsList = JsonConvert.DeserializeObject<Dictionary<string, string>>(data); Is this how you are talking about? It gives me error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. Commented Mar 29, 2018 at 14:45
  • 1
    No, I told you that your JSON is a list of Dictionary<string, string> Commented Mar 29, 2018 at 14:45

1 Answer 1

1

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

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

1 Comment

Thanks I understood what was missing now.

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.