MiniJosn的使用案例

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值