Reputation: 99
Currently, I am trying to parse some JSON I receive from an API. Here are some results I get back:
{
"2": {
"id": 2,
"name": "Cannonball",
"members": true,
"sp": 5,
"buy_average": 152,
"buy_quantity": 358914,
"sell_average": 151,
"sell_quantity": 778131,
"overall_average": 152,
"overall_quantity": 1137045
},
"6": {
"id": 6,
"name": "Cannon base",
"members": true,
"sp": 187500,
"buy_average": 184833,
"buy_quantity": 9,
"sell_average": 180518,
"sell_quantity": 10,
"overall_average": 182562,
"overall_quantity": 19
}
}
I need to parse it to a C# class. I tried copying the JSON and with paste special converting it to a class, but then it creates an class for every JSON object.
Does someone have any tips on how I can parse it so it's only 1 class? The properties are always the same, it is just the object "2":
that is the problem.
Upvotes: 0
Views: 634
Reputation: 788
The JSON you provided consists of two objects, not one. You can parse it into a Dictionary with JsonConvert.DeserializeObject<Dictionary<int, YourClass>>(jsonString)
. You will then have a dictionary with two entries, with keys 2
and 6
.
Upvotes: 3
Reputation: 118937
The trick here is to deserialise to a Dictionary
of your class type. For example:
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
public bool Members { get; set; }
// etc...
}
And now you would deserialise like this:
var result = JsonConvert.DeserializeObject<Dictionary<string, Thing>>(json);
Note: you could probably use Dictionary<int, Thing>
here if it's guaranteed to be numbers.
Upvotes: 4