这个问题在这里已经有一个答案:>
How to handle both a single item and an array for the same property using JSON.net5个
我正在使用雅虎幻想运动api.我得到这样的结果:
我正在使用雅虎幻想运动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不支持反序列化数组“.
我也试过转过公共字符串的位置{get;组; } to public string [] position {get;组; }但我仍然收到错误.
我该如何处理?
解决方法
我将使用
Json.Net.这个想法是:“将位置声明为List< string>,如果json中的值是一个字符串,然后将其转换为List”
反序列化代码
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; } }