来自 Unity 的 JSON 序列化不正确(正在使用数组和包装器)



虽然我可以使用 JsonUtility 序列化/反序列化简单数据,但在尝试将对象数组加载到我的游戏中时,Unity 的响应不佳。

我确实了解该实用程序不接受数组,因此需要替代解决方案。 我已经尝试使用此处发布的包装器(谢谢!!),但它仍然没有达到我期望的效果。

虽然我将所有详细信息传递到 JSON 中,但在保存它时,它只保存实例 ID,这对于持久性不是很有用。

这是一步一步。

1. 创建对象

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. 保存 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. 附加信息

  • Customer 类是 System.Serializable 的,与其中引用的资源组相同。
  • 这是生成的 json

    {"Items":[{"instanceID":-47734},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0}]}

首先尝试从Customer类中删除MonoBehaviour继承。此外,Unity 的默认序列化程序不支持Dictionary<>序列化。尝试从字典更改为可序列化类列表。还要检查所有内部客户数据字段是否也是可序列化的。

最新更新