Fetbi Irsat Fetbi Irsat - 3 months ago 28
C# Question

Parse dynamic JSON

I am using c# and json.net 9.0.1

I have the following json

{
"lineups": [
{
"55": {
"id": "55",
"game_id": "1",
"player_id": "55",
"jersey_number": "78"
},
"56": {
"id": "56",
"game_id": "1",
"player_id": "56",
"jersey_number": "77"
},
"57": {
"id": "57",
"game_id": "1",
"player_id": "57",
"jersey_number": "76"
}
}
]
}


All of the array items are of type Player. How can I parse the json so that each item "55", "56", "57" are stored in a list of Players, List?

The source json can't be modified as it is coming from a 3rd party.

UPDATE
Modified the json to be valid,

Answer

If you created two classes like this:

public class Lineup
{
    public List<Dictionary<string,Player>> lineups;
}

public class Player
{
    public string id {get; set; }
    public string game_id { get; set;}
    public string player_id {get;set;}
    public string jersey_number {get;set;}
}

Then you should (after you've fixed your invalid JSON), be able to deserialize like this:

var l = Newtonsoft.Json.JsonConvert.DeserializeObject<Lineup>(source);

Example: https://dotnetfiddle.net/e7eUUZ

You can also use the various attributes in JSON.Net to customize the deserialization. For example, you might want to use the JsonPropertyAttribute to map the names in your JSON source to C# property names that match the standard.