C#反序列化Cryptocompare接口JSON触发JsonSerializationException,求解决
解决JSON反序列化对象到数组的错误问题
我来帮你分析问题根源,一步步搞定这个反序列化错误:
错误核心原因
你遇到的JsonSerializationException本质是类型不匹配:
Cryptocompare接口返回的是一个单个JSON对象(结构类似{"Response":"Success", "Data":[...], ...}),但你手动把返回内容包装成了{ "Arr": + www.text + "}",同时你的CurrencyContainer类里的Arr字段定义为Example[](数组类型)。当Newtonsoft.Json尝试把单个对象转成数组时,自然就会抛出异常。
修复步骤
1. 移除多余的JSON包装层
完全没必要给接口返回的JSON加{ "Arr": ... }这一层,直接用原响应字符串反序列化即可。
2. 调整变量类型与反序列化逻辑
把原来的CurrencyContainer container改成Example container,然后在协程里直接反序列化:
IEnumerator GetText() { using (WWW www = new WWW("https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD")) { yield return www; if (www.error != null) { Debug.Log("Error is : " + www.error); } else { // 直接反序列化到Example类,去掉多余包装 container = JsonConvert.DeserializeObject<Example>(www.text); } } }
3. 推荐:替换弃用的WWW类
Unity的WWW在2017.2版本后已被标记为弃用,建议改用更稳定的UnityWebRequest:
IEnumerator GetText() { using (UnityWebRequest www = UnityWebRequest.Get("https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD")) { yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.Log("Error is : " + www.error); } else { container = JsonConvert.DeserializeObject<Example>(www.downloadHandler.text); } } }
4. 修正调试代码
原来的Debug.Log(container.Arr)要改成访问Example类的属性,比如:
void Update() { if (container != null) { Debug.Log($"请求状态:{container.Response},数据条目数:{container.Data.Count}"); } else { Debug.Log ("null"); } }
完整修改后的核心代码
public class StockManager : MonoBehaviour { private Example container; [SerializeField]private int currenciesToLoad; void Start() { StartCoroutine(GetText()); } void Update() { if (container != null) { Debug.Log($"请求状态:{container.Response},数据条目数:{container.Data.Count}"); } else { Debug.Log ("null"); } } IEnumerator GetText() { using (UnityWebRequest www = UnityWebRequest.Get("https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD")) { yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.Log("Error is : " + www.error); } else { container = JsonConvert.DeserializeObject<Example>(www.downloadHandler.text); } } } [System.Serializable] public class Datum { public int time; public double close; public double high; public double low; public double open; public double volumefrom; public double volumeto; } [System.Serializable] public class ConversionType { public string type; public string conversionSymbol; } [System.Serializable] public class Example { public string Response; public int Type; public bool Aggregated; public IList<Datum> Data; public int TimeTo; public int TimeFrom; public bool FirstValueInArray; public ConversionType ConversionType; } // 不再需要CurrencyContainer类,可直接删除 }
这样修改后,反序列化就能正常工作了——现在是把单个JSON对象匹配到对应的Example类实例,而不是错误地试图转成数组。
内容的提问来源于stack exchange,提问作者weaverbeaver
相关产品推荐
相关产品推荐

