Why is my object null when trying to parse a json string to said object

Viewed 297

I'm trying to parse some json data which looks like this:

{
  "2": {
    "id": 2,
    "name": "Cannonball",
    "members": true,
    "sp": 5,
    "buy_average": 172,
    "buy_quantity": 210800,
    "sell_average": 174,
    "sell_quantity": 326435,
    "overall_average": 174,
    "overall_quantity": 537235
  },
  "6": {
    "id": 6,
    "name": "Cannon base",
    "members": true,
    "sp": 187500,
    "buy_average": 185130,
    "buy_quantity": 1,
    "sell_average": 181300,
    "sell_quantity": 3,
    "overall_average": 182257,
    "overall_quantity": 4
  }
}

And I'm using the following model

class BuySellModel
{
    public int id { get; set; }
    public string name { get; set; }
    public bool members { get; set; }
    public int sp { get; set; }
    public int buy_average { get; set; }
    public int buy_quantity { get; set; }
    public int sell_average { get; set; }
    public int sell_quantity { get; set; }
    public int overall_average { get; set; }
    public int overall_quantity { get; set; }
}

Now the way I am trying to parse it is by using JSON.NET in order to get each and every single item as a .NET object in a collection of some sort, so kinda like List<BuySellModel>

However.. When I try parsing it doing this

var BuySellObjects = JsonConvert.DeserializeObject<BuySellModel>(buySellDataString);

each property in BuySellObjects is then null and I don't understand why.

Could someone explain why each property is null and here I went wrong?

2 Answers

Try using this as your model

    public class ParsableModel
    {
       public Dictionary<int, BuySellModel> BuySellObjects { get; set; }
    }

your json looks like a dictionary of int and BuySellModel

you can try this

var dictionary = JsonConvert.DeserializeObject<IDictionary<int, BuySellModel>>(buySellDataString);
var allBuySellObjects = dictionary.Values; // flatten all the values into a list
Related