1.使用LitJson解析数据,保存数据为json
csharp
// 创建一个字典用来给读取json后赋值
public Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
public void LoadDeviceDic()
{
string filePath = Path.Combine(Application.persistentDataPath, "dData.json");
// 检查文件是否存在
if (File.Exists(filePath))
{
// 从文件中读取 JSON 数据
string json = File.ReadAllText(filePath);
// 将 JSON 数据转换为字典
myDictionary = JsonMapper.ToObject<Dictionary<string, List<string>>>(json);
Debug.Log("Dictionary data loaded from: " + filePath);
DeviceManager.GetInstance().myDictionary = myDictionary;
// 示例:输出加载的数据
foreach (var pair in myDictionary)
{
Debug.Log("Key: " + pair.Key + ", Value: " + pair.Value + ", " + pair.Value);
}
}
else
{
Debug.LogError("Dictionary data file not found!");
}
}
保存数据为json
csharp
public static void SaveDiviceDicdate(Dictionary<string, List<string>> pairs)
{
JsonData jsonData = JsonMapper.ToJson(pairs);
// 获取文件路径
string filePath = Path.Combine(Application.persistentDataPath, "dData.json");
Debug.LogWarning(jsonData.ToString());
// 保存 JSON 字符串到文件
// File.WriteAllText(filePath, jsonData.ToString(), Encoding.UTF8);
File.WriteAllText(filePath, jsonData.ToString(), Encoding.UTF8);
Debug.Log("Dictionary data saved to: " + filePath);
}