How can I deserialize this JSON with JsonConvert?

前端 未结 2 1098
北海茫月
北海茫月 2020-12-11 23:17

I have this JSON and I cannot figure out how to convert it to a List of objects in C#.

Here is the JSON:

{
  \"2\": {
    \"sell_average\": 239,
            


        
相关标签:
2条回答
  • 2020-12-11 23:18

    You can use

    var dict = JsonConvert.DeserializeObject<Dictionary<int, ItemSummary>>(json);
    var items = dict.Values.ToList();  //if you want a List<ItemSummary>;
    
    0 讨论(0)
  • 2020-12-11 23:19
    public class ItemSummaryModel
    {
        [JsonProperty(PropertyName = "2")]
        public ItemSummary Two { get; set; }
        [JsonProperty(PropertyName = "6")]
        public ItemSummary Six { get; set; }
        [JsonProperty(PropertyName = "8")]
        public ItemSummary Eight { get; set; }
    }
    
    var result = JsonConvert.DeserializeObject<ItemSummaryModel>(json);
    

    This will technically work to get you a complex object, but I don't much like it. Having numbers for property names is going to be an issue. This being json for a single complex object will also be tricky. If it were instead a list, you could begin writing your own ContractResolver to handle mapping the number property name to an id field and the actual object to whatever property you wanted.

    0 讨论(0)
提交回复
热议问题