MiniJosn的使用案例

来源:互联网 发布:优道网络骗局揭秘 编辑:程序博客网 时间:2024/06/07 06:33

MiniJson的使用案例


在Unity中使用的时候,需要导入一个MiniJson脚本,放在Plugins目录下:
这里写图片描述


Json文件格式如下:

[{"id":1,"name":"\u5218\u5fb7\u534e","lv":100,"hp":1000},{"id":2,"name":"\u9ece\u660e","lv":44,"hp":1000},{"id":3,"name":"\u5f20\u5b66\u53cb","lv":66,"hp":200}]

MiniJson 的代码实现 :

using System.Collections;using System.Collections.Generic;using System.IO;using UnityEngine;public class JsonDemo : MonoBehaviour{    private List<Role> roleList;    private List<Dictionary<string, object>> list;    private List<Role> roleList_parsed;    void Start()    {        roleList = new List<Role>();        roleList.Add(new Role { id = 1, name = "刘德华", lv = 100, hp = 1000 });        roleList.Add(new Role { id = 2, name = "黎明", lv = 44, hp = 1000 });        roleList.Add(new Role { id = 3, name = "张学友", lv = 66, hp = 200 });        ///序列化 把数据以json的形式存入一个txt文本        list = new List<Dictionary<string, object>>();        foreach (var item in roleList)        {            Dictionary<string, object> dic = new Dictionary<string, object>();            dic.Add("id", item.id);            dic.Add("name", item.name);            dic.Add("lv", item.lv);            dic.Add("hp", item.hp);            list.Add(dic);        }        string jsonStr = MiniJSON.Json.Serialize(list);        File.WriteAllText(Application.dataPath + "/a.txt", jsonStr);        print(jsonStr);        ///反序列化        print("======================");        roleList_parsed = new List<Role>();        List<object> obj = MiniJSON.Json.Deserialize(jsonStr) as List<object>;        foreach (var item in obj)        {            print(item);            Dictionary<string, object> d = item as Dictionary<string, object>;            Role r = new Role();            r.id = int.Parse(d["id"].ToString());            r.name = d["name"].ToString();            roleList_parsed.Add(r);        }        ///把解析的结果输出下        print("==========解析的结果=======");        foreach (var item in roleList_parsed)        {            print(string.Format("id:{0}  name:{1}", item.id, item.name));        }    }}public class Role{    public int id;    public string name;    public int age;    public int lv; //等级    public int hp;}

插件下载链接:https://pan.baidu.com/s/1i4V1v1b 密码:f82b


原创粉丝点击