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.

