Unity3D JSON反序列化空列表? [英] Unity3D JSON Deserializing Empty List?

查看:213
本文介绍了Unity3D JSON反序列化空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回空列表(只是[])的Web服务.

I have a web service that returns an empty list (just []).

JsonUtility.FromJson给我一个

ArgumentException:JSON必须表示一个对象类型.

ArgumentException: JSON must represent an object type.

我已将其隔离为一些简单的代码,例如:

I have isolated this down to a bit of code as simple as:

string empty = "[]";
FriendManager.FriendList test = JsonUtility.FromJson<FriendManager.FriendList>(empty);
Assert.IsNotNull(test);

FriendList只是Friend[]的包装.我也尝试过List<Friend>:

FriendList is just a wrapper for Friend[]. I also tried List<Friend>:

string empty = "[]";
FriendManager.FriendList test = JsonUtility.FromJson<List<Friend>>(empty);
Assert.IsNotNull(test);

我缺少明显的东西吗?

我可以控制服务器数据(Spring Boot JSON Web服务)和客户端(Unity3D).

I have control over the server data (Spring Boot JSON web service) and the client (Unity3D).

推荐答案

来自

您不能直接将JsonUtility与List之类的类型一起使用,而必须将其与已定义的类或结构类型一起使用

You can't use JsonUtility with a type like List directly, you have to use it with a defined class or struct type

因此您的第二次尝试将无法进行.如果您说的是List<Friend>类型,也不能直接将其分配给FriendManager.FriendList.

so your second attempt will not work. And you also cannot directly asign it to FriendManager.FriendList if it s of type List<Friend> as you said.

您宁愿为此需要一个包装器类,例如

You rather need a wrapper class for it like e.g.

[Serializable]
public class FriendList
{
    public List<Friend> Friends = new List<Friend>();
}

使类型FriendList

除了服务器之外,您还必须将字段名称附加到该数组,即变量名称:Friends例如喜欢

And than either the server or you have to append the field name to that array namely the name of the variable: Friends e.g. like

FriendManager.FriendList test = JsonUtility.FromJson<List<Friend>>("\"Friends\":" + empty);

或者服务器必须发送

"Friends":[]

这篇关于Unity3D JSON反序列化空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆