Search code examples
c#jsonjson.net

Deserializing JSON to C# class where property names in the JSON are dynamic


I'm using the JSON.NET package to deserialize a JSON response to a C# class but the json is oddly formatted. They are sending back an array of items where each item's name property is set to be the ID (weird because as you can see below, the ID already appears in the body of the object as 'player_id'). Like this:

{
    "5131": {
        "player_id": 5131,
        "prop1": "val1",
        "prop2": null,
        "prop3": "val3"
    },
    "5132": {
        "player_id": 5132,
        "prop1": "val1",
        "prop2": null,
        "prop3": "val3"
    }
}

Normally you'd would have a name-value pair where the name is something standard like 'player' and you'd have the id as a property in object.

Is there a way to define a C# class around this that it will deserialize into what I need (just an array of items, no dynamically named id props). Thanks


Solution

  • Since each object has a player_id that matches the object key values, you don't need to worry about capturing the object keys. I'd just serialize it to a Dictionary first, and then just take the values from that dictionary.

    var players = JsonConvert.DeserializeObject<Dictionary<string, Player>>(input).Values;