Unity中要导入litjson
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;
[System.Serializable]
public class PassConfig
{
public List<PassInfo> passInfo = new List<PassInfo>();
public PassProp passProp = new PassProp();
}
[System.Serializable]
public class PassInfo
{
//等级
public int Id;
//关卡名字
public string Name;
public PassProp passProp;
}
[System.Serializable]
public class PassProp
{
//道具ID
public int ID;
public string PropName;
}
public class JsonSerializeTest : MonoBehaviour
{
private string jsonDir;
private string jsonFileName = "Mekey.json";
private string jsonPath;
/// <summary>
///面板观察反序列化对象数据
/// </summary>
public PassConfig _passConfig;
void Start()
{
jsonDir = Application.persistentDataPath + "/JsonDir";
jsonPath = jsonDir + "/" + jsonFileName;
PassConfig passConfig = new PassConfig();
passConfig.passInfo = new List<PassInfo>();
for (int i = 0; i < 5; i++)
{
PassInfo passInfo = new PassInfo();
passInfo.passProp = new PassProp();
passInfo.passProp.ID = i * 50;
passInfo.passProp.PropName = "MeKey" + i * 100;
passInfo.Id = i;
passInfo.Name = "MeKey -> " + i;
passConfig.passInfo.Add(passInfo);
}
passConfig.passProp.ID = 50000;
passConfig.passProp.PropName = "MeKey+++++++50000";
SaveJson(passConfig);
LoadJson();
}
/// <summary>
/// 保存数据
/// </summary>
/// <param name="passConfig"></param>
public void SaveJson(PassConfig passConfig)
{
if (!Directory.Exists(jsonDir))
{
Directory.CreateDirectory(jsonDir);
}
if (!File.Exists(jsonPath))
{
//如果第一次创建并且写入文件 要Dispose
File.Create(jsonPath).Dispose();
}
string json = JsonMapper.ToJson(passConfig);
StreamWriter sw = new StreamWriter(jsonPath);
sw.Write(json);
sw.Close();
#if UNITY_EDITOR //打开本地沙盒路径
Debug.Log("创建文件成功,路径:--->" + jsonDir);
System.Diagnostics.Process.Start(jsonDir);
#endif
}
/// <summary>
/// 读取保存数据的方法
/// </summary>
public void LoadJson()
{
if (!File.Exists(jsonPath))
{
Debug.LogError("不存在此文件");
return;
}
StreamReader streamReader = new StreamReader(jsonPath);
string json = streamReader.ReadToEnd();
streamReader.Close();
_passConfig = JsonMapper.ToObject<PassConfig>(json);
Debug.Log("读取成功");
}
}