C#实现读取写入Json文件
暗夜__ 人气:0C#读取写入Json文件
/// <summary> /// 将序列化的json字符串内容写入Json文件,并且保存 /// </summary> /// <param name="path">路径</param> /// <param name="jsonConents">Json内容</param> private void WriteJsonFile(string path, string jsonConents) { File.WriteAllText(path, jsonConents, System.Text.Encoding.UTF8); } /// <summary> /// 获取到本地的Json文件并且解析返回对应的json字符串 /// </summary> /// <param name="filepath">文件路径</param> /// <returns></returns> private string GetJsonFile(string filepath) { string json = string.Empty; using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { json = sr.ReadToEnd().ToString(); } } return json; } /// <summary> /// 对象 转换为Json字符串 /// </summary> /// <param name="tablelList"></param> /// <returns></returns> public string toJson(object tablelList) { DataContractJsonSerializer json = new DataContractJsonSerializer(tablelList.GetType()); string finJson = ""; //序列化 using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, tablelList); finJson = Encoding.UTF8.GetString(stream.ToArray()); } Debug.Log(tablelList + "JSON数据为:" + finJson); return finJson; }
将数据写入Json文件中
部分逻辑代码
//需要写入Json文件中的数据集合 List<MonsterSpawnPoint> MonsterPos = new List<MonsterSpawnPoint>(); //转为string 字符串 string text = toJson(MonsterPos); //写入Json文件 filepath文件路径 string filepath=Path.Combine(Application.dataPath, "../", "Config_NPC.json"); WriteJsonFile(filepath, text);
Json文件
[ { "Direction": 0, "Index": 9, "PositionX": 28, "PositionY": 10, "PositionZ": 20 }, { "Direction": 0, "Index": 9, "PositionX": 40, "PositionY": 10, "PositionZ": 18 }, { "Direction": 0, "Index": 4, "PositionX": 21, "PositionY": 10, "PositionZ": -8 }, { "Direction": 0, "Index": 4, "PositionX": 40, "PositionY": 10, "PositionZ": -13 } ]
读取Json文件
Json对应的数据结构
public class MonsterSpawnPoint { public long Index;//怪物索引 public int PositionX;//怪物X坐标 public int PositionY;//怪物Y坐标 public int PositionZ;//怪物Z坐标 public int Direction; } //读取指定数据集合Json MonsterSpawnPoint[] monsterPoints = LitJson.JsonMapper.ToObject<MonsterSpawnPoint[]>(GetJsonFile(filepath)); //读取Json 通过字符串 索引取得Json表中的值 LitJson.JsonData jsonData = LitJson.JsonMapper.ToObject(GetJsonFile(fillePath)); foreach (JsonData item in jsonData) { JsonData id_data = item["Id"];//通过字符串 索引取得键值对的值 JsonData name_data = type == InitType.Monster ? item["Name"] : item["NPCName"];//通过字符串 索引取得键值对的值 tempData = new Dropdown.OptionData(); tempData.text = $"[{id_data}]{name_data}"; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容