Home > Net >  Deserialize list of dictionaries | C#
Deserialize list of dictionaries | C#

Time:01-12

I have an object from api

{
  "1569801600000": 260174000000,
  "1601424000000": 274515000000,
  "1632960000000": 365817000000,
  "1664496000000": 394328000000,
  "index": "CarIndex"
},
{
  "1569801600000": 260174000000,
  "1601424000000": 274515000000,
  "1632960000000": 365817000000,
  "1664496000000": 394328000000,
  "index": "BooksIndex"
},
{
  "1569801600000": 161782000000,
  "1601424000000": 169559000000,
  "1632960000000": 212981000000,
  "1664496000000": 223546000000,
  "index": "TablesIndex"
},

In my api response I have 32 such items, here on example only 3.

As you can see here list of keyValuePair. I tried such case

var objectResult = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(resultString);

have exception.

I tried such case

var objectResult = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(resultString);

have exception.

In future this keys 1569801600000 can be different so I cant create [JsonProperty("1569801600000") in model. Can you help me?

CodePudding user response:

this is working for me

List<Dictionary<string, string>> objectResult = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);

but if you want a list of key value pairs

List<List<KeyValuePair<string,string>>>  objectResult = JArray.Parse(json)
                                   .Select(i=> ((JObject)i).Properties()
                                   .Select(ja => new KeyValuePair<string, string>(
                                        ja.Name, ja.Value.ToString() )).ToList()
                                    ).ToList();
  • Related