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}

{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?

You must use type Sub instead Base:

Debug.LogFormat(“{0}
{1}”, JsonUtility.FromJson<Base>(sB), JsonUtility.FromJson<Sub>(sS));

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.