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}
{1}“, b, s);
Debug.LogFormat(”{0}
{1}“, sB, sS);
Debug.LogFormat(”{0}
{1}", JsonUtility.FromJson(sB), JsonUtility.FromJson(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?