The “new” class JsonUtility provides easy-to-use JSON (de-)serialization. In this “early” state, it doesn’t support arrays as type to directly serialize. However, there is a workaround using wrapper classes (as seen in this post on StackOverflow).
In my project, I have an array of objects that extend an abstract class, but JsonUtility doesn’t seem to do anything with it.
using System;
using UnityEngine;
public class JsonTest : MonoBehaviour {
void Start () {
// The array that contains elements based on AbstractBase
AbstractBase[] array = new AbstractBase[]
{
new SubOne(),
new SubTwo()
};
// Print one element
string json = JsonUtility.ToJson(array[0]);
Debug.Log(json);
// Print array
json = JsonUtility.ToJson(array);
Debug.Log(json);
// Print random array (that does not have an abstract class as it's type) using wrapper
ArrayWrapper<string> stringWrapper = new ArrayWrapper<string>();
stringWrapper.items = new string[] { "one", "two"};
json = JsonUtility.ToJson(stringWrapper);
Debug.Log(json);
// Print abstract array using wrapper
ArrayWrapper<AbstractBase> abstractWrapper = new ArrayWrapper<AbstractBase>();
abstractWrapper.items = array;
json = JsonUtility.ToJson(abstractWrapper);
Debug.Log(json);
}
}
public class ArrayWrapper<T>
{
public T[] items;
}
[Serializable]
public abstract class AbstractBase
{
public string name;
}
[Serializable]
public class SubOne : AbstractBase
{
public int someImportantInt = 2;
}
[Serializable]
public class SubTwo : AbstractBase
{
public string someImportantString = "I'm important!";
}
The log prints the following json-strings:
{"name":"","someImportantInt":2}
{}
{"items":["one","two"]}
{}
This points out that JsonUtility doesn’t serialize bare arrays (as seen in line 2) and arrays with an abstract type.
So, is this a bug or does anyone know a workaround for this?