小编典典

如何处理同时返回字符串和字符串数组的json?[重复]

c#

我正在使用Yahoo Fantasy体育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; }
}

当我运行此命令时,由于合格的位置可以同时返回一个字符串和一个字符串数组,因此我不断收到错误消息“数组反序列化不支持类型’System.String’”。

我也尝试过转向public string position { get; set; }public string[] position { get; set; }但仍然出现错误。

我该如何处理?


阅读 337

收藏
2020-05-19

共1个答案

小编典典

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

反序列化的代码

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

Json转换器

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

样本杰森

{
    "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; }
}
2020-05-19