- Home /
How does JsonUtility.FromJson() handle Inheritance?
How do I read json with inherited types to the proper sub types?
public class JsonTest : MonoBehaviour
{
void Start ()
{
Base b = new Base() { id = 1, name = "Bob" };
Sub s = new Sub() { id = 2, name = "Builder", age = 5, number = 123.345f };
string sB = JsonUtility.ToJson(b);
string sS = JsonUtility.ToJson(s);
Debug.LogFormat("{0}\n{1}", b, s);
Debug.LogFormat("{0}\n{1}", sB, sS);
Debug.LogFormat("{0}\n{1}", JsonUtility.FromJson<Base>(sB), JsonUtility.FromJson<Base>(sS));
}
}
[Serializable]
public class Base
{
public long id;
public string name;
public override string ToString()
{
return String.Format("[id:{0}, name:{1}]", id, name);
}
}
[Serializable]
public class Sub : Base
{
public int age;
public float number;
public override string ToString()
{
return String.Format("[id:{0}, name:{1}, age:{2}, number:{3}]", id, name, age, number);
}
}
Output
ToString() -- Works as expected
[id:1, name:Bob]
[id:2, name:Builder, age:5, number:123.345]JsonUtility.ToJson() -- works as expected
{"id":1,"name":"Bob"}
{"id":2,"name":"Builder","age":5,"number":123.34500122070313}JsonUtility.FromJson() -- doesn't deserialize sub types
[id:1, name:Bob]
[id:2, name:Builder]
Is there any way to do this?
Answer by sheld · Dec 22, 2015 at 08:58 AM
You must use type Sub instead Base:
Debug.LogFormat("{0}\n{1}", JsonUtility.FromJson<Base>(sB), JsonUtility.FromJson<Sub>(sS));
Answer by superpig · Jan 06, 2016 at 02:36 AM
JsonUtility deserializes to the exact type you tell it to - no subclasses.
This means you will need to either know what type your JSON data represents, or you will need to deserialise it multiple times - once into a type that lets you figure out what kind of data it is, and then a second time into the appropriate subclass type.