Search code examples
c#arraysjsondeserialization

How to deserialize it?


{
  "success": true,
  "time": 1668509701,
  "currency": "RUB",
  "items": {
    "186150629_143865972": {
      "price": "278.61",
      "buy_order": 251.72,
      "avg_price": "284.900000",
      "popularity_7d": "10",
      "market_hash_name": "CS:GO Case Key",
      "ru_name": "Ключ от кейса CS:GO",
      "ru_rarity": "базового класса",
      "ru_quality": "",
      "text_color": "D2D2D2",
      "bg_color": ""
    },
    "36150629_143865972": {
      "price": "278.61",
      "buy_order": 251.72,
      "avg_price": "284.900000",
      "popularity_7d": "10",
      "market_hash_name": "CS:GO Case Key",
      "ru_name": "Ключ от кейса CS:GO",
      "ru_rarity": "базового класса",
      "ru_quality": "",
      "text_color": "D2D2D2",
      "bg_color": ""
    },
  }
}

Don't go out and create a class structure for deserialization via JsonConvert.DeserializeObject(jsonString); Nested entities 186150629_143865972 may be different, their structure is always the same, but the names are unique.

I'm trying to do something like this but it doesn't work...

public class Item
{
    public string price { get; set; }
    public double buy_order { get; set; }
    public string avg_price { get; set; }
    public string popularity_7d { get; set; }
    public string market_hash_name { get; set; }
    public string ru_name { get; set; }
    public string ru_rarity { get; set; }
    public string ru_quality { get; set; }
    public string text_color { get; set; }
    public string bg_color { get; set; }
}

public class Root
{
    public bool success { get; set; }
    public int time { get; set; }
    public string currency { get; set; }
    public List<Item> items { get; set; }
}

Solution

  • According to your json, the items property should be a dictionary, not a list.

    public class Root
    {
        public bool success { get; set; }
        public int time { get; set; }
        public string currency { get; set; }
        public Dictionary<string, Item> items { get; set; } = new();
     }
    

    Also, another thing I would mention is that properties should be capitalized (see naming conventions in documentation) and combined with JsonProperty attribute.

    [JsonProperty("market_hash_name")] 
    public string MarketHashName { get; set; }
    

    instead of

    public string market_hash_name { get; set; }