Unity3D JSON Deserializing Empty List?

2019-08-18 05:20发布

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

JsonUtility.FromJson is giving me an

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 is just a wrapper for Friend[]. I also tried List<Friend>:

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

Am I missing something obvious?

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

标签: json unity3d
1条回答
Animai°情兽
2楼-- · 2019-08-18 06:17

From this thread

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

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>();
}

make FriendManaget.FriendList of type FriendList

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);

or the server has to send

"Friends":[]
查看更多
登录 后发表回答