unity3D技术分享Unity3D

数据存储(三)Json的存储与解析

2018-08-17  本文已影响34人  无赖宵小

说明:

Json一般使用两个类库,一个System.Json(便于Json生成),一个是LitJson(便于Json解析)。

Json生成实例:

void LitCtreatJson()

{   

        JsonData hero = new JsonData();

        hero["HeroName"] = "诺克萨斯";

        hero["Hp"] = 100;

        hero["attack"] = 40;

        hero["Skills"] = new JsonData();

        JsonData skill1 = new JsonData();

        skill1["KeyCode"] = "Q";

        skill1["Name"] = "大杀四方";

        skill1["Mp"] = 20;

        skill1["cd"] = 8;

        hero["Skills"].Add(skill1);

        JsonData skill2 = new JsonData();

        skill2["KeyCode"] = "W";

        skill2["Name"] = "致残打击";

        skill2["Mp"] = 40;

        skill2["cd"] = 5;

        hero["Skills"].Add(skill2);

        JsonData skill3 = new JsonData();

        skill3["KeyCode"] = "E";

        skill3["Name"] = "无情铁手";

        skill3["Mp"] = 10;

        skill3["cd"] = 9;

        hero["Skills"].Add(skill3);

        JsonData skill4 = new JsonData();

        skill4["KeyCode"] = "R";

        skill4["Name"] = "诺克萨斯断头台";

        skill4["Mp"] = 120;

        skill4["cd"] = 60;

        hero["Skills"].Add(skill4);

}

Json解析实例:

 void LitParseJson()

{

        FileInfo file =new FileInfo(Application.dataPath + "/LoL.json");

        StreamReader sr = new StreamReader(file.OpenRead(), Encoding.UTF8);

        string content = sr.ReadToEnd();

        JsonData data= JsonMapper.ToObject(content);

        foreach (JsonData item in data["Skills"])

        {

            print(item["name"]);

        }

        Hero hero;

        hero =  JsonUtility.FromJson(content);

        sr.Close();

        sr.Dispose();

 }

上一篇下一篇

猜你喜欢

热点阅读