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.

4
  • The way your JSON is structured I think you definitely want it to parse to an IEnumerable<YourClass> 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. Commented Aug 6, 2019 at 13:00
  • Possible duplicate of How to auto-generate a C# class file from a JSON object string Commented Aug 6, 2019 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. Commented Aug 6, 2019 at 13:07
  • @Liam I disagree. Not the same question. Commented Aug 6, 2019 at 14:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.