本文共 4012 字,大约阅读时间需要 13 分钟。
json 官网:http://www.json.org/json-zh.html01:生成text文本
[ { "id": 1, "name": "BeJson", "damage": 30 }, { "id": 2, "name": "嘿嘿嘿", "damage": 100 }, { "id": 3, "name": "嘿嘿嘿", "damage": 200 }]
02:解析
class Program { static void Main(string[] args) { string text = File.ReadAllText("JsonData.txt"); //data代表一个数组 JsonData data=JsonMapper.ToObject(text); //item代表一个对象 foreach (JsonData item in data) { int id = int.Parse(item["id"].ToString()); string name = item["name"].ToString(); int damage = int.Parse(item["damage"].ToString()); Console.WriteLine("id:" + id + "name:" + name + "damage:" + damage); } Console.ReadKey(); } }03:使用泛型解析(json里面的属性值和对应类里面的属性值要保持一致)
namespace Json解析02{ class Program { static void Main(string[] args) { string text = File.ReadAllText("JsonData.txt"); Skill[] skills=JsonMapper.ToObject(text); foreach (Skill skill in skills) { Console.Write(skill.id); Console.WriteLine(); Console.Write(skill.name); Console.WriteLine(); Console.Write(skill.damage); } Console.ReadKey(); } } public class Skill { public int id; public string name; public int damage; }}
04:当text是一个对象时候的解析
//Player.txt
{ "Name": "二连", "Level": 500, "Age": 20, "SkillList": [ { "id": 1, "name": "BeJson", "damage": 30 }, { "id": 2, "name": "嘿嘿嘿", "damage": 100 }, { "id": 3, "name": "嘿嘿嘿", "damage": 200 } ]}
namespace Json解析02{ class Program { static void Main(string[] args) { string text = File.ReadAllText("Player.txt"); Player player=JsonMapper.ToObject(text); Console.WriteLine(player.Age); Console.WriteLine(player.Name); Console.WriteLine(player.Level); foreach (var item in player.SkillList) { Console.WriteLine(item); } Console.ReadKey(); } } public class Skill { public int id; public string name; public int damage; public override string ToString() { return $"{nameof(id)}: {id}, {nameof(name)}: {name}, {nameof(damage)}: {damage}"; } } public class Player { public string Name; public int Level; public int Age; public List SkillList; public override string ToString() { return $"{nameof(Name)}: {Name}, {nameof(Level)}: {Level}, {nameof(Age)}: {Age}, {nameof(SkillList)}: {SkillList}"; } }}
public void SaveLevelFileByJson() { LevelInfo levelInfoGo = CreateLevelInfoGo(); string filePath = Application.streamingAssetsPath + "/Json/Level/" + "Level" + bigLevelID.ToString() + "_" + levelID.ToString() + ".json"; string saveJsonStr = JsonMapper.ToJson(levelInfoGo); StreamWriter sw = new StreamWriter(filePath); sw.Write(saveJsonStr); sw.Close(); }#endif //读取关卡文件解析json转化为LevelInfo对象 public LevelInfo LoadLevelInfoFile(string fileName) { LevelInfo levelInfo = new LevelInfo(); string filePath=Application.streamingAssetsPath+ "/Json/Level/" + fileName; if (File.Exists(filePath)) { StreamReader sr = new StreamReader(filePath); string jsonStr = sr.ReadToEnd(); sr.Close(); levelInfo = JsonMapper.ToObject(jsonStr); return levelInfo; } Debug.Log("文件加载失败,加载路径是"+filePath); return null; }
转载地址:http://acrxo.baihongyu.com/