Unity_LitJson_088

来源:互联网 发布:开源搜索引擎源码 编辑:程序博客网 时间:2024/06/05 15:45

前几篇博客写了有关Json数据的解析,今天在那古来LitJson学习一下吧,整体上来说LitJson比Unity自带的要强大很多。

using System.Collections;using System.Collections.Generic;using UnityEngine;using LitJson;//数据模型public class Student{    public string name;    public int age;    public char gender;    /*     *  在解析json数据的时候,  数据模型类中不能包含构造方法  只能在创建对象的饿时候一个一个赋值     *  否则抛出异常  MissingMethodException: Method not found: 'Default constructor not found...ctor() of Student'.     *       */     /*    public Student(string name, int age, char gender)    {        this.name = name;        this.age = age;        this.gender = gender;    }    */}public class LitJsonTest : MonoBehaviour {    // Use this for initialization    void Start () {        //生成比较简单的游戏Json数据        JsonData jd = new JsonData();        jd["name"] = "yy";        jd["age"] = 19;        //生成Json 数据  {"name":"yy","age":19}        Debug.Log(jd.ToJson());        //生成嵌套的游戏对象        JsonData data = new JsonData();        data["name"] = "yy";        data["age"] = 18;        data["hobby"] = new JsonData();        data["hobby"]["read"] = "《童年》";        data["hobby"]["sport"] = "篮球";        //生成的Json数据 格式如下        //{"name":"yy","age":18,"hobby":{"read":"\u300A\u7AE5\u5E74\u300B","sport":"\u7BEE\u7403"}}        //由于数据中含有中文,内部对中文采用的是Unicode编码        Debug.Log(data.ToJson());        //将json解析到JsonJata        string jsonStr = data.ToJson();        JsonData jsondata = JsonMapper.ToObject(jsonStr);        //打印结果  yy  《童年》        Debug.Log(jsondata["name"] +"  "+ jsondata["hobby"]["read"]);        //使用JsonMapper 将对象直接映射到json格式的数据        Student stu = new Student();        //在类中不能写构造方法        stu.name = "Jack";        stu.age = 12;        stu.gender = '男';        string json = JsonMapper.ToJson(stu);        Debug.Log(json);        //将json数据映射到对象        Student stu1 = JsonMapper.ToObject<Student>(json);        Debug.Log(stu1.name +"  |" +stu1.age +"  |"+stu1.gender);    }}
原创粉丝点击