neuecc/Utf8Json

Json string of "array of Child classes" not as expected

Kotsuha opened this issue · 1 comments

Hello. I was searching for a way to serialize an array of objects into JSON string and then I found this library. This is my first time trying out. I try the code below in Unity 2019.4.24f1

public class TestJsonUtility : MonoBehaviour
{
    [ContextMenu("Test Json")]
    private void TestToJson()
    {
        var objs1 = new Parent[]
        {
            new Child1(),
            new Child2(),
        };
        var json1 = JsonSerializer.ToJsonString(objs1);
        Debug.Log("Json1:");
        Debug.Log(json1);

        var objs2 = new object[]
        {
            new Child1(),
            new Child2(),
        };
        var json2 = JsonSerializer.ToJsonString(objs2);
        Debug.Log("Json2:");
        Debug.Log(json2);
    }

    [Serializable]
    public class Parent
    {
        public string dummyString = "Hello";
    }

    [Serializable]
    public class Child1 : Parent
    {
        public int dummyInt = 120;
    }

    [Serializable]
    public class Child2 : Parent
    {
        public bool dummyBool = true;
    }
}

In the console

Json1:
[{"dummyString":"Hello"},{"dummyString":"Hello"}]
Json2:
[{"dummyInt":120,"dummyString":"Hello"},{"dummyBool":true,"dummyString":"Hello"}]

I actually want the second result but I expect to get it in the first one. Would like to know if this is by design? Or am I missing something? Thanks.

I realized if I want to Deserialize them to exact Child type later, it's more convenient to Serialize them with exact type in the first place. Maybe this question can be closed.