Search Unity

Deserialize JSON empty list?

Discussion in 'Scripting' started by GainfulSage, Dec 11, 2018.

  1. GainfulSage

    GainfulSage

    Joined:
    Apr 30, 2015
    Posts:
    106
    Hi -

    I'm trying to deserialize an empty JSON array, and I'm getting an ArgumentException: JSON must represent an object type.

    I have tried both a simple wrapper class, e.g.

    Code (CSharp):
    1. string empty = "[]";
    2. FriendManager.FriendList test =
    3.       JsonUtility.FromJson<FriendManager.FriendList>(empty);
    4. Assert.IsNotNull(test);
    and also a regular List, e.g.

    Code (CSharp):
    1. string empty = "[]";
    2. FriendManager.FriendList test =
    3.       JsonUtility.FromJson<List<Friend>>(empty);
    4. Assert.IsNotNull(test);
    ...and either way when I try to deserialize the string "[]" via JsonUtility.FromJson I get the exception. Am I missing something obvious, or is this expected behavior?
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Unity's Json serializer is pretty limited and my recollection is that it can't cope with naked arrays. You can have an object that contains an array, but the top-level construct in the original JSON needs to be an object.

    Code (CSharp):
    1. string exampleJson = "{ \"myArray\": [] }"
     
    TaleOf4Gamers and GainfulSage like this.