Unity解析C# API返回JSON数组时触发ArgumentException错误
Unity解析ASP.NET API JSON数组报错解决方案
问题根源
Unity自带的JsonUtility不支持直接解析顶级JSON数组(即根节点为[]的JSON),它要求JSON根节点必须是一个对象({}包裹)。你的API返回的是顶级Profile数组,而你尝试用包含数组的ProfileList类去解析,就会触发ArgumentException: JSON must represent an object type.错误。单个对象能正常解析是因为它本身就是符合要求的对象结构。
解决方法
方法1:修改API返回结构(优先推荐,若有权限)
让ASP.NET API返回一个包含数组的对象,而非直接返回数组:
{ "profileList": [ {"id":1,"name":"name1","avatar":"avatar1","theme":"jungle"}, {"id":2,"name":"name2","avatar":"avatar2","theme":"space"}, {"id":3,"name":"name3","avatar":"avatar3","theme":"jungle"}, {"id":4,"name":"name4","avatar":"avatar4","theme":"space"} ] }
修改后你的现有Unity代码无需改动,JsonUtility.FromJson<ProfileList>即可正常解析。
方法2:在Unity端预处理JSON字符串(无法修改API时使用)
子方案2.1:给JSON套对象外壳后解析
直接在Unity代码中给返回的数组JSON包裹一层对象结构,匹配你的ProfileList类:
// 替换原解析代码 string wrappedJson = "{\"profileList\":" + responseText + "}"; profileList = JsonUtility.FromJson<ProfileList>(wrappedJson);
子方案2.2:使用辅助类直接解析数组
编写一个通用JSON辅助类,专门处理顶级数组解析:
public static class JsonHelper { public static T[] FromJson<T>(string json) { string wrappedJson = "{\"items\":" + json + "}"; Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(wrappedJson); return wrapper.items; } [System.Serializable] private class Wrapper<T> { public T[] items; } }
然后在请求回调中使用:
// 替换原解析代码 Profile[] profiles = JsonHelper.FromJson<Profile>(responseText); // 若需要存入ProfileList对象 profileList.profileList = profiles;
内容的提问来源于stack exchange,提问作者stevenWalters
相关产品推荐
相关产品推荐

