简体   繁体   中英

Deserialize list of dictionaries | C#

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM