Ok, I have to admit, I’ve a problem with JSON files, and I’m working with JS from a long time so maybe I’m a bit confused
I shoud create a simple JSON file like that:
public class MainData {
public string videoFolder;
public Email email;
}
public class Email
{
public string from;
public string to;
}
Now I should create the JSON file, so:
public class SaveData : MonoBehaviour
{
public void SaveIntoJson()
{
MainData mainData = new MainData();
mainData.videoFolder = "empty";
mainData.email = new Email();
mainData.email.from = "empty";
mainData.email.to = "empty";
string configFile = JsonUtility.ToJson(mainData, true);
System.IO.File.WriteAllText(Application.dataPath + "/config.json", configFile);
}
}
In Unity I obviously can get all “data” from mainData.email.from, and mainData.email.to,
but these values are not written in the JSON file, so what I get is that:
public static class Globals
{
[Serializable]
public class MainData
{
public string videoFolder;
public Email email = new Email();
}
[Serializable]
public class Email
{
public string from;
public string to;
}
}
public class SaveData : MonoBehaviour
{
public void SaveIntoJson()
{
string configFileName = "config.json";
Globals.MainData mainData = new Globals.MainData();
string configFile = JsonUtility.ToJson(mainData, true);
System.IO.File.WriteAllText(Application.persistentDataPath + "/" + configFileName, configFile);
}
}
The key point you’re missing is that Unity JSON is SUPER limited. It’s like ultra light Fisher Price kindergarten JSON.
Problems with Unity “tiny lite” built-in JSON:
In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.
Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).
PS: for folks howling about how NewtonSoft JSON .NET will “add too much size” to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work in the year 2021.
Many thanks Kurt-Dekker, for sure I’ll give a look to the package and links that you’ve suggested.
For this specific project I don’t have too big requirements, so for my needs this simple solution is enough.
With JS structured data are a lot more easy to manage, but this is another story (and that’s why sometimes,
moving back and forth from JS and Unity C# can become quite hard ;))