52 lines
1.5 KiB
C#
52 lines
1.5 KiB
C#
using UnityEngine;
|
||
using Newtonsoft.Json;
|
||
using System.IO;
|
||
|
||
public static class JsonManager
|
||
{
|
||
/// <summary>
|
||
/// 保存数据 PC端
|
||
/// </summary>
|
||
/// <param name="data">需要存储的数据对象</param>
|
||
/// <param name="fileName">存储为的文件名</param>
|
||
/// <param name="type">存储方式,默认LitJson</param>
|
||
public static void SaveData(object data, string fileName)
|
||
{
|
||
//存储路径
|
||
string path = Application.streamingAssetsPath + "/" + fileName + ".json";
|
||
//序列化 得到json字符串
|
||
string json = "";
|
||
json = JsonConvert.SerializeObject(data);
|
||
//把json字符串保存成文件
|
||
File.WriteAllText(path, json);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取数据 PC端
|
||
/// </summary>
|
||
/// <typeparam name="T">类型</typeparam>
|
||
/// <param name="path"></param>
|
||
/// <returns></returns>
|
||
public static T LoadData<T>(string fileName) where T : new()
|
||
{
|
||
//路径
|
||
string path = Application.streamingAssetsPath + "/" + fileName + ".json";
|
||
if (!File.Exists(path))
|
||
{
|
||
path = Application.persistentDataPath + "/" + fileName + ".json";
|
||
}
|
||
if (!File.Exists(path))
|
||
{
|
||
return new T();
|
||
}
|
||
//获取json字符串
|
||
string jsonStr = File.ReadAllText(path);
|
||
|
||
//
|
||
T data = new T();
|
||
//反序列
|
||
data = JsonConvert.DeserializeObject<T>(jsonStr);
|
||
return data;
|
||
}
|
||
}
|