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

c#, json

Solution

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

Problem

I'm using the Yahoo fantasy sports api. I'm getting a result like this: ``` "player": [ { ... "eligible_positions": { "position": "QB" }, ... }, { ... "eligible_positions": { "position": [ "WR", "W/R/T" ] }, ... }, ``` How is it that I can deserialize this? My code looks like this: ``` var json = new JavaScriptSerializer(); if (response != null) { JSONResponse JSONResponseObject = json.Deserialize<JSONResponse>(response); return JSONResponseObject; } ``` And in my JSONResponse.cs file: ``` public class Player { public string player_key { get; set; } public string player_id { get; set; } public string display_position { get; set; } public SelectedPosition selected_position { get; set; } public Eligible_Positions eligible_positions { get; set; } public Name name { get; set; } } public class Eligible_Positions { public string position { get; set; } } ``` When I run this, since eligible_positions can return both a string and a string array, I keep getting the error "Type 'System.String' is not supported for deserialization of an array". I've also tried turning `public string position { get; set; }` to `public string[] position { get; set; }` but I still get an error. How should I handle this?

Original source

Related problems