如何处理返回字符串和字符串数组的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" ] } } ] }
类(简化版)
上述就是C#学习教程:如何处理返回字符串和字符串数组的json?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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; } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1002208.html