如何处理返回字符串和字符串数组的json?

yge*_*rts 9 c# json

我正在使用Yahoo fantasy sports api.我得到这样的结果:

"player": [
    {
        ...
        "eligible_positions": {
            "position": "QB"
        },
        ...
    },
    {
        ...
        "eligible_positions": {
            "position": [
                "WR",
                "W/R/T"
            ]
        },
        ...
    },
Run Code Online (Sandbox Code Playgroud)

我怎么能反序化呢?

我的代码看起来像这样:

var json = new JavaScriptSerializer();

if (response != null)
{
    JSONResponse JSONResponseObject = json.Deserialize<JSONResponse>(response);
    return JSONResponseObject;
}
Run Code Online (Sandbox Code Playgroud)

在我的JSONResponse.cs文件中:

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; }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,由于qualified_positions可以返回字符串和字符串数组,我不断得到错误"类型'System.String'不支持反序列化数组".

我也试过转向public string position { get; set; },public string[] position { get; set; }但我仍然收到错误.

我该怎么处理?

L.B*_*L.B 14

我会用Json.Net.这个想法是:"声明position为a List<string>,如果json中的值是一个字符串.然后将其转换为List"

用于反序列化的代码

var api = JsonConvert.DeserializeObject<SportsAPI>(json);
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

示例Json

{
    "player": [
        {
            "eligible_positions": {
                "position": "QB"
            }
        },
        {
            "eligible_positions": {
                "position": [
                    "WR",
                    "W/R/T"
                ]
            }
        }
    ]
}   
Run Code Online (Sandbox Code Playgroud)

类(简化版)

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; }
}
Run Code Online (Sandbox Code Playgroud)