While I could serialize/deserialize simple data with JsonUtility, when trying to load an array of objects into my game, Unity didn't respond well.
I do understand that the utility doesn't take arrays, so alternative solutions are needed. I've tried using the wrapper posted here (Thanks!!), but it's still not doing what I'd expect it to do.
While I'm passing all the details into the JSON, when saving it, it's only saving instanceIDs, which are not very useful for persistency.
Here's the step by step.
1. Creating the object
private Customer[] _customerDeck;
Customer yidler = new GameObject().AddComponent<Customer>();
yidler.race = GameController.Race.Alien;
yidler.initial = true;
yidler.patience = 3;
yidler.dice = new ResourceGroup();
yidler.dice.diceRequired = 1;
yidler.dice.resources = new Dictionary<GameController.Resource, int>();
yidler.dice.resources.Add(GameController.Resource.Food, 3);
yidler.dice.resources.Add(GameController.Resource.Beverage, 0);
yidler.dice.resources.Add(GameController.Resource.Dessert, 1);
yidler.moneyAwarded = 6;
yidler.fidelityAwarded = 1;
yidler.starsAwarded = 0;
yidler.initial = true;
_customerDeck[0] = yidler;
JSONManager.SaveCustomers(_customerDeck);
2. Saving the JSON
public static void SaveCustomers(Customer[] customers)
{
string filePath = Path.Combine(Application.streamingAssetsPath, customerCardsFile);
if(File.Exists(filePath))
{
string data = JsonHelper.ToJson<Customer>(customers);
File.WriteAllText(filePath, data);
}
else
{
Supporting.Log("Cannot find Customers JSON", 1);
}
}
public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
[System.Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
3. Additional Info
- The Customer class is System.Serializable, same as the ResourceGroup referenced within it.
This is the resulting json
{"Items":[{"instanceID":-47734},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0}]}