数学建模 C#如何实现读取写入Json文件 - PositionX&#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力平台 👁️ 594 次阅读

本文主要介绍了C#实现读取写入Json文件方式,具有很好的参考价值,希望对大家有所帮助。

C#读取写入Json文件

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 ///

/// 将序列化的json字符串内容写入Json文件,并且保存 /// ///路径///Json内容private void WriteJsonFile(string path, string jsonConents) { File.WriteAllText(path, jsonConents, System.Text.Encoding.UTF8); } ////// 获取到本地的Json文件并且解析返回对应的json字符串 /// ///文件路径///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; } ////// 对象 转换为Json字符串 /// //////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文件中

部分逻辑代码 拼多多帮助力入口

1 2 3 4 5 6 7 //需要写入Json文件中的数据集合 ListMonsterPos = new List(); //转为string 字符串 string text = toJson(MonsterPos); //写入Json文件 filepath文件路径 string filepath=Path.Combine(Application.dataPath, "../", "Config_NPC.json"); WriteJsonFile(filepath, text);

Json文件

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [ { "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对应的数据结构

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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(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}"; }

总结

以上为个人经验,希望能给大家一个参考,也希望

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧