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

时间:2014-02-26 20:22:59

标签: c# json

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

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

我怎么能反序化呢?

我的代码如下所示:

var json = new JavaScriptSerializer();

if (response != null)
{
    JSONResponse JSONResponseObject = json.Deserialize<JSONResponse>(response);
    return JSONResponseObject;
}

在我的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; }
}

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

我也尝试将public string position { get; set; }转为public string[] position { get; set; },但我仍然收到错误消息。

我应该如何处理?

1 个答案:

答案 0 :(得分:14)

我将使用Json.Net。我的想法是:“将position声明为List<string>,如果json中的值是字符串,则将其转换为列表”

反序列化代码

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

示例Json

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

课程(简化版)

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