0

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,

2
  • deserialize it to a Dictionary<string,Player> where your keys 55, 56, etc will become the keys in the dictionary. Commented Aug 23, 2016 at 19:59
  • 8
    The JSON in your example isn't valid JSON... (opening { inside the lineups array, but no corresponding closing) Do you really need to parse malformed JSON, or is the example bad? Please edit the question to clarify. Commented Aug 23, 2016 at 20:01

2 Answers 2

3

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.

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

Comments

1

Given these classes:

public class Lineup
{
    public List<Player> Players { get; set; }
}

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; }
}

public class Result
{
    public List<Lineup> Lineups { get; set; }
}

You could implement a custom JsonConverter like this:

public class LineupConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Lineup);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        if (reader.TokenType != JsonToken.StartObject)
            throw new Exception("Expected an object");

        var jObject = (JObject)JObject.ReadFrom(reader);

        // I suspect the property name are the same as the id property
        // of the contained objects. Discarding the information from serialization
        var players = jObject.Properties()
            .Select(p => p.Value.ToObject<Player>());

        return new Lineup
        {
            Players = players.ToList()
        };

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

And then use:

var lineups = JsonConvert.DeserializeObject<Result>(json, new LineupConverter());

You could also annotate the Player properties with JsonProperty attributes and have them more C#-like.

2 Comments

Custom parser is an overkill. See @Matt Burland's answer.
@Shiva I agree a parser is an overkill in this case. I believe giving an alternative will at least make Fetbi aware of his options should he encounter another case that might warrant the use of a custom Converter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.