How to handle json that returns both a string and a string array? [duplicate]

I’ll use Json.Net. The idea is: “declare position as a List<string> and if the value in json is a string. then convert it to a List”

Code to deserialize

var api = JsonConvert.DeserializeObject<SportsAPI>(json);

JsonConverter

public class StringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
    {

        if(reader.ValueType==typeof(string))
        {
            return new List<string>() { (string)reader.Value };
        }
        return serializer.Deserialize<List<string>>(reader);
    }

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

Sample Json

{
    "player": [
        {
            "eligible_positions": {
                "position": "QB"
            }
        },
        {
            "eligible_positions": {
                "position": [
                    "WR",
                    "W/R/T"
                ]
            }
        }
    ]
}   

Classes (Simplified version)

public class EligiblePositions
{
    [JsonConverter(typeof(StringConverter))] // <-- See This
    public List<string> position { get; set; }
}

public class Player
{
    public EligiblePositions eligible_positions { get; set; }
}

public class SportsAPI
{
    public List<Player> player { get; set; }
}

Leave a Comment