Recursive JSON serialization / serialize list of custom serializable objects?
So I have an object oriented structure I'm trying to save to a json so it can be manually configured and have basically the setup outlined below:
[Serializable]
class DataPoint
{
public string value;
}
[Serializable]
class Data
{
public DataPoint[] datapoints;
}
public virtual void SaveConfig()
{
Data d = new Data()
{
datapoints = new DataPoint[Values.Length]
};
int i = 0;
foreach (string v in Values)
{
DataPoint e = new DataPoint ()
{
value = v;
};
d.datapoints[i] = e;
i++;
}
string fpath = GetConfigFilePath() + "/" + GetConfigFileName() + ".json";
File.WriteAllText(fpath, JsonUtility.ToJson(d, true));
}
With the above code nothing gets serialized; the file only has '{}'. If I change datapoints to a string array and change:
d.datapoints[i] = e;
to
d.datapoints[i] = JsonUtility.ToJson(e, true);
I get serialized data, but it's ugly and I plan on adding custom classes to the DataPoint class and want to have a serialization that is recursive. I read that Unity supports serializing arrays and List classes as long as their Serializable, but I can't see it in practice. Any help is appreciated.
Answer by agray427 · Jan 16, 2018 at 07:53 PM
I recommend using Json.NET. It stores everything in JSON, which is what you are currently attempting to do, and it will maintain the polymorphism of derived types. I wrote an entire article on it. Check it out here: https://graymattertutorials.wordpress.com/2018/01/15/serialization-with-json-net-in-unity-3d/