json转换时,如果第一次没有数据,需要传null或者空"{}"
json.PNG
我尝试用json保存list发现保存不了,转为json时为空,上网搜了一下,又问了大佬,发现如果要支持List和Array,建议写一个包装类,将其包含再里边,并且泛型中加入[Serializable]标签。如果要支持Dictionary,建议改写成List。
包装类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ListCollection
{
public List<PetInfo> PetInfo;
}
应用:
//构造解析json
PetController()
{
string jsonPet = GameData.Instance.GetString("PetInfos", "{}");
Debug.Log("string jsonPet:" + jsonPet);
if (jsonPet != null)
{
try
{
ListCollection list = JsonUtility.FromJson<ListCollection>(jsonPet);
petInfos = list.PetInfo;
Debug.Log("petInfos:" + petInfos.Count);
}
catch (System.Exception ex)
{
Debug.Log(ex.Message);
throw;
}
//JsonData _str = JsonMapper.ToObject(jsonPet);
}
}
//保存宠物
public void Save()
{
Debug.Log("save:" + petInfos.Count);
//转json
var collection = new ListCollection()
{
PetInfo = petInfos
};
GameData.Instance.SetString("PetInfos", JsonUtility.ToJson(collection));
Debug.Log("save:" + JsonUtility.ToJson(collection));
}