0

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.

Lews Therin
  • 3,707
  • 2
  • 27
  • 53
  • The way your JSON is structured I think you definitely want it to parse to an `IEnumerable` specifically because the properties are the same. Why do you want this to come in as one class with duplicate keys? At the end of the day you're just creating a class that pretends to be a List. – DetectivePikachu Aug 06 '19 at 13:00
  • Possible duplicate of [How to auto-generate a C# class file from a JSON object string](https://stackoverflow.com/questions/21611674/how-to-auto-generate-a-c-sharp-class-file-from-a-json-object-string) – Liam Aug 06 '19 at 13:01
  • 1
    @Liam I don't think that's a useful dupe here, OP is basically there, but is stuck with the dynamic property names. – DavidG Aug 06 '19 at 13:07
  • @Liam I disagree. Not the same question. – Viggo Lundén Aug 06 '19 at 14:16

2 Answers2

4

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
3

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.

Viggo Lundén
  • 748
  • 1
  • 6
  • 31