在现有的Json表中添加新的数据,我这里的Json数据是集合的形式,思路是先读取现有的本地Json,转成对象进行操作,然后对该对象进行处理添加新资源,最后再将对象保存为Json。
Json表中的部分数据截图
public class Tb_File
{
public string FILE_ID;
public string FILE_NAME;
public string TYPE;
public string PATH;
}
public class AddJsonData : MonoBehaviour
{
private StreamReader streamreader;
private JsonReader js;
private string jsonPath;
private Tb_File Tb_File;
private List<Tb_File> tb_FileList=new List<Tb_File>();
private Dictionary<string, List<Tb_File>> tb_fileDic = new Dictionary<string, List<Tb_File>>();
void Start()
{
Tb_File = new Tb_File();
//测试
// WriteTo_Tb_File("1","2","3","4");
}
//1、先将Json保存成Dic方式
//2、再添加新的数据
//3、再将字典存为Json
/// <summary>
/// 写入TB_FILEjson表
/// </summary>
/// <param name="File_Id"></param>
/// <param name="File_Name"></param>
/// <param name="Type"></param>
/// <param name="Path"></param>
public void WriteTo_Tb_File(string File_Id,string File_Name,string Type,string Path)
{
jsonPath = Application.streamingAssetsPath + "/SQLJson/tb_file.json";
streamreader = new StreamReader(jsonPath);//读取数据,转换成数据流
js = new JsonReader(streamreader);//再转换成json数据
//JsonData tb_FileRecords = JsonMapper.ToObject(streamreader.ReadToEnd());//读取
tb_fileDic = JsonMapper.ToObject<Dictionary<string, List<Tb_File>>>(streamreader.ReadToEnd());//读取
tb_FileList = tb_fileDic["RECORDS"];
if (streamreader != null)
{
streamreader.Close();
}
//存入新的Dic
Tb_File.FILE_ID = File_Id;
Tb_File.FILE_NAME = File_Name;
Tb_File.TYPE = Type;
Tb_File.PATH = Path;
tb_FileList.Add(Tb_File);
tb_fileDic["RECORDS"] = tb_FileList;
Debug.Log("添加新数据");
string values = JsonMapper.ToJson(tb_fileDic);
FileStream file = new FileStream(jsonPath, FileMode.Create);
byte[] bts = System.Text.Encoding.UTF8.GetBytes(values);
file.Write(bts, 0, bts.Length);
if (file != null)
{
file.Close();
}
Debug.Log("保存成Json成功");
AssetDatabase.Refresh();
}