0

When using JsonUtility to serialize in Unity, List of a class will be serialized as empty string if it's filled with subclasses of ExampleObjtype.

    [Serializable]
    public class SerializableGameEntityDebugSubclass : SerializableGameEntityDebug {
        public SerializableGameEntityDebugSubclass() : base() {}
    }

    [Serializable]
    public abstract class SerializableGameEntityDebug {
        public string uuid = null;

        public SerializableGameEntityDebug() {
            this.uuid = "debuggin";
        }
    }
public class GameSaveData 
{
    public List<GameEntity.SerializableGameEntityDebugSubclass> serializableGameEntitiesDebug1 = new List<GameEntity.SerializableGameEntityDebugSubclass>{ new SerializableGameEntityDebugSubclass() };
    public List<GameEntity.SerializableGameEntityDebug> serializableGameEntitiesDebug2 = new List<GameEntity.SerializableGameEntityDebug>{ new SerializableGameEntityDebugSubclass() };
}

serializableGameEntitiesDebug1 DOES get subclassed and serializableGameEntitiesDebug1 does NOT get subclassed. I find this very odd because even if I print out individually the serialized elements of the list, it works correctly in both cases.

pete
  • 1,878
  • 2
  • 23
  • 43
  • 1
    Unity uses the [regular serializer for its JSON](https://docs.unity3d.com/Manual/JSONSerialization.html) as well. If you want to use a better option, you may want to use the [Json.NET package](https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@2.0/manual/index.html). – Max Play Feb 01 '22 at 22:13

1 Answers1

1

There are two separate issues at play.

  1. It seems JsonUtility won't serialize List of any abstract class no matter what. So the thing the list contains must not be an abstract class
  2. When I change the abstract class to a regular class, it will serialize it, but it will only contain fields in the base class rather than child classes.

Therefore it seems the only workaround is to have many lists to serialize (one for each child class)

Update: A slightly more elegant solution was to switch from using JsonUtility to Json.net JsonConverter. This caused serialization to work perfectly, but not yet deserialization. I still had to write a converter class so the deserializer knows which class to instantiate. I followed this answer and it worked. Last but not least it seems that each serializable class needs to have a default empty constructor for the deserializer to call when trying to instantiate it before hydrating it, or else it might try to call other constructors with null args

pete
  • 1,878
  • 2
  • 23
  • 43