How can I deserialize this JSON with JsonConvert?

核能气质少年 提交于 2019-12-17 21:32:13

问题


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,
    "buy_average": 238,
    "overall_average": 240,
    "id": 2
  },
  "6": {
    "sell_average": 184434,
    "buy_average": 182151,
    "overall_average": 189000,
    "id": 6
  },
  "8": {
    "sell_average": 11201,
    "buy_average": 1723,
    "overall_average": 180,
    "id": 8
  }
}

And the code I've tried using:

public class ItemSummaryModel
{
    public string Id { get; set; }
    public ItemSummary ItemSummary { get; set; }
}

public class ItemSummary
{
    public int Sell_Average { get; set; }
    public int Buy_Average { get; set; }
    public int Overall_Average { get; set; }
    public int Id { get; set; }
}

List<ItemSummaryModel> models =
    JsonConvert.DeserializeObject<List<ItemSummaryModel>>(jsonSummary);

to no avail. How can I deserialize this JSON into lists of these objects using Newtonsoft's JSON library (Json.Net)?


回答1:


You can use

var dict = JsonConvert.DeserializeObject<Dictionary<int, ItemSummary>>(json);
var items = dict.Values.ToList();  //if you want a List<ItemSummary>;



回答2:


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.



来源:https://stackoverflow.com/questions/37450215/how-can-i-deserialize-this-json-with-jsonconvert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!