Unity背包系统(一)使用LitJson库创建并解析Json文件
发表于2018-03-20
这是一个和大家介绍背包系统的系列文章,主要是帮助大家去掌握背包系统的开发。游戏基本都有背包系统存在,对于开发者来说要知道如何去做一个背包系统,搭建一个背包系统框架。本篇文章就和大家介绍下使用LitJson这个库来创建并解析Json文件。
首先下载LitJson.dll。
新建Plugins目录,将LitJson.dll拖进去
【创建Json文件】
引用LitJson库
using LitJson;
生成Json文件
List<KnapsackGood> list = new List<KnapsackGood>(); BaseProperty baseProperty_Ring = new BaseProperty(1, "Ring", "传说\n天山梅戒 攻击 +10 防御 +100\n\nwww.liujunliang.com.cn by 即歩", 10, 100, 80, "UI/Good (1)", KnapsackGood.GoodType.Consumable, KnapsackGood.GoodQuality.Common); Consumable good_Ring = new Consumable(10, 10, baseProperty_Ring);//其中Consumable继承自KnapsackGood list.Add(good_Ring); string json = JsonMapper.ToJson(list);//生成Json文件 //将json写入到文件 string path = Application.streamingAssetsPath + "/GoodJson.json"; StreamWriter sw = new StreamWriter(path); sw.Write(json); sw.Close();
这样创建了一个Json文件,其中保存了两个变量和一个类
【解析Json文件】
同样需要引用LitJson库
using LitJson;
解析Json文件
List<KnapsackGood> goodList = new List<KnapsackGood>(); //读取文件 string path = Application.streamingAssetsPath + "/GoodJson.json"; StreamReader sr =new StreamReader(path); string json=sr.ReadToEnd(); sr.Close(); JsonData data = JsonMapper.ToObject(json); BaseProperty gp = JsonMapper.ToObject<BaseProperty>(data[i]["goodProperty"].ToJson()); int HP = int.Parse(data[i]["HP"].ToString()); int MP = int.Parse(data[i]["MP"].ToString()); Consumable kg = new Consumable(HP,MP,gp); List<KnapsackGood> goodList = goodList.Add(kg);
将类和两个变量解析出来了