Is there any way to serialize referenced MonoBehaviours to JSON?

Viewed 1230

Let's say I have an object called ObjectA which contains two objects: ObjectsB and ObjectC.

[System.Serializable]
public ClassA
{
    public ClassB classB;
    public ClassC classC;

    public ClassA()
    {
        classB = new ClassB();
        classC = new ClassC();
    }
}

[System.Serializable]
public ClassB
{
    //Some fields.
}

[System.Serializable]
public ClassC
{
    //Some fields.
}

If I serialize ObjectA to JSON, ObjectB and ObjectC don't get serialized. This is what I've got after serializing ObjectA to JSON:
{"_instanceB":{"instanceID":10480},"_instanceC":{"instanceID":10230}}
I need to serialize all these objects to a file and save it locally on hard drive to be able to restore their states later. How can I do it?
Am I supposed to retrieve ClassB and ClassC from ClassA then serialize and save them individually? Something like this:

public void Save()
{
    //Get instances of ClassB and ClassC.
    ClassB classB = classA.GetClassB;
    ClassC classC = classA.GetClassC;

    //Generate different JSON for each class.
    string classA_JSON = JsonUtility.ToJson(classA);
    string classB_JSON = JsonUtility.ToJson(classB);
    string classC_JSON = JsonUtility.ToJson(classC);

    //Paths for saving locally.
    string pathForClassA = Path.Combine("C:\\", "classA.json");
    string pathForClassB = Path.Combine("C:\\", "classB.json");
    string pathForClassC = Path.Combine("C:\\", "classC.json");

    File.WriteAllText(pathForClassA, classA_JSON);
    File.WriteAllText(pathForClassB, classB_JSON);
    File.WriteAllText(pathForClassC, classC_JSON);
}

Looks ugly and it will generate a new JSON file for each nested class. Can I somehow serialize ClassA including its nested classes into one JSON file?

P.S. This is a Unity project and ClassA, ClassB, and ClassC derive from MonoBehaviour. Since BinaryFormatter doesn't support MonoBehaviour I can't use it. The only thing that left for me is to serialize it to JSON.

1 Answers

Can I somehow serialize ClassA including its nested classes into one JSON file?

Yes you could but it would require some work:

You could have [Serializable] representation classes for ClassB and ClassC and use the ISerializationCallbackReceiver interface for filling and using them in ClassA

Something like e.g.

public class ClassB : MonoBehaviour
{
    [SerializeField] private float example1;
    [SerializeField] private string example2;
    // etc.

    public void SetUp(SerializableClassB values)
    {
        // set all values
        this.example1 = values.example1;
        this.example2 = values.example2;
        // etc.
    }

    public SerializableClassB GetSerializable()
    {
        var output = new SerializableClassB();

        output.example1 = this.example1;
        output.example2 = this.example2;
        // etc.

        return output;
    }
}

[Serializable]
public class SerializableClassB
{
    public float example1;
    public string example2;
    // etc
}

And the same for ClassC

public class ClassC : MonoBehaviour
{
    [SerializeField] private float example3;
    [SerializeField] private string example4;
    // etc.

    public void SetUp(SerializableClassC values)
    {
        // set all values
        example3 = values.example3;
        example4 = values.example4;
        // etc.
    }

    public SerializableClassC GetSerializable()
    {
        var output = new SerializableClassC();

        output.example3 = example3;
        output.example4 = example4;
        // etc.

        return output;
    }
}

[Serializable]
public class SerializableClassC
{
    public float example3;
    public string example4;
    // etc
}

Then in ClassA you can do

public class ClassA : MonoBehaviour, ISerializationCallbackReceiver
{
    public ClassB _classB;
    public ClassC _classC;

    [SerializeField] private SerializableClassB _serializableClassB;
    [SerializeField] private SerializableClassC _serializeableClassC;


    public void OnBeforeSerialize()
    {
        // before writing to a Json get the information from the MonoBehaviours into the normal classes
        if(_classB) _serializableClassB = _classB.GetSerializable();
        if(_classC) _serializeableClassC = _classC.GetSerializable();

    }

    public void OnAfterDeserialize()
    {
        // after deserializing write the infromation from the normal classes into the MonoBehaviours
        if(_classB) _classB.SetUp(_serializableClassB);
        if(_classC) _classC.SetUp(_serializeableClassC);
    }
}

The second huge advantage (side-effect) is that now you additionally can also controll the values of _classB and _classC directly on the ClassA instance. This way you can modify MonoBehaviour values in a centralized manager class.

enter image description here

After serializing to json using

private void Start()
{
    File.WriteAllText(Path.Combine(Application.streamingAssetsPath, "Test.txt"), JsonUtility.ToJson(this));
    AssetDatabase.Refresh();
}

you now get

{
    "_classB":{"instanceID":-6766},"_classC":{"instanceID":-6826},
    "_serializableClassB": {
            "example1":23.0,
            "example2":"54ththfghg"
    },
    "_serializeableClassC": {
            "example3":67.0,
            "example4":"567gffhgfhgf"
    }
}

Than for the example I changed it to

{
    "_classB":{"instanceID":-6766},"_classC":{"instanceID":-6826},
    "_serializableClassB": {
            "example1":47,
            "example2":"Hello"
    },
    "_serializeableClassC": {
            "example3":32.123,
            "example4":"World!"
    }
}

and deserialized on start from json using

private void Start()
{
    JsonUtility.FromJsonOverwrite(File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "Test.txt")), this);
}

enter image description here

Related