如何处理返回字符串和字符串数组的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(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; } public string position { get; set; } to public string[] position { get; set; } public string[] position { get; set; } 但我仍然得到一个错误。

我该怎么处理?

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

用于反序列化的代码

 var api = JsonConvert.DeserializeObject(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)reader.Value }; } return serializer.Deserialize>(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 position { get; set; } } public class Player { public EligiblePositions eligible_positions { get; set; } } public class SportsAPI { public List player { get; set; } }