I'm looking for how to save the variable that defined as base class to json.
[Serializable]
class DataFile
{
public Node root;
public void Save()
{
ParentNode root = new ParentNode();
root.m_Childs = new Node[2]();
root.m_Name = "Root";
ParentNode node0 = new ParentNode();
ParentNode node1 = new ParentNode();
node0.m_Name = "Node0";
node1.m_Name = "Node1";
root.m_Childs[0] = node0;
root.m_Childs[1] = node1;
JSonUtility.ToJson(this);
}
}
[Serializable]
class Node
{
public string m_Name;
}
[Serializable]
class ParentNode : Node
{
public Node[] m_Childs;
}
The resulting JsonUtility with the above code only stores m_Name of root and m_Childs not.
How can I figure it out?
When you serialize you are serializing the value of
public Node root;
which only has a
public string m_Name;
not the local variable
ParentNode root = new ParentNode();
Additionally the (de)serializer will use the type you give it, not the type it could possibly be by inheritance. The only type known to DataFile is Node so it will only serialize fields known to that type. And the only type known to ParentNode are childs of type Node. If you need to store the information contained in a ParentNode then you'll have to use fields of that type instead!
I guess it should maybe rather be
[Serializable]
class DataFile
{
public ParentNode root;
public void Save()
{
var node0 = new ParentNode{
m_Name = "Node0"
};
var node1 = new ParentNode{
m_Name = "Node1"
};
root = new ParentNode{
m_Name = "Root",
m_Childs = new[]{node0, node1}
};
JSonUtility.ToJson(this);
}
}
[Serializable]
class Node
{
public string m_Name;
}
[Serializable]
class ParentNode : Node
{
// Again the only type known to ParentNode is childs of type Node
// if you need ParentNode then the type has to be that also in the
// ParentNode class
public ParentNode[] m_Childs;
}
As with other json libraries, the Json Utility, which is provided by Unity by default, was unable to determine what type of content was stored when load from json. I have decided to use scriptable object, but if you really want to use Json Utility, you can use ISerializationCallbackReceiver to make commands before and after Json serialization.