Unity3D LitJson 使用方法

原创文章如需转载请注明:转载自 脱莫柔Unity3D学习之旅 QQ群:【Unity3D(AR/VR) 334163814】【Unity3D(游戏) 119706192】 本文链接地址: LitJson 使用方法

119706192-QQ群共享提供下载


对象与Json互转:

void OnGUI()
    {
        if (GUI.Button(new Rect(10,10,100,20),"ClassToJson"))
        {
            ClassToJson();
        }
        if (GUI.Button(new Rect(10, 40, 100, 20), "JsonToClass"))
        {
            JsonToClass();
        }
    }

    string JsonString;
    public void ClassToJson()
    {
        teseClass temp = new teseClass();
        temp.name = "名字";
        temp.age = 22;
        temp.isMan = true;
        temp.testList = new List<int>() { 3, 6, 9 };

        JsonString = JsonMapper.ToJson(temp);

        //Log
        Debug.Log("ClassToJson:" + JsonString);
    }
    public void JsonToClass()
    {
        teseClass temp = JsonMapper.ToObject<teseClass>(JsonString);

        //Log
        string log = "name:" + temp.name + ":" + temp.age;
        if (temp.isMan) log += "|男|";else log += "|女|";
        log += "testList{";
        for (int i = 0; i < temp.testList.Count; i++)
        {
            if (i!= 0) log += ",";
            log += temp.testList[i].ToString();
        }
        log += "}";
        Debug.Log(log);
    }

    public class teseClass
    {
        public string name;
        public int age;
        public bool isMan;
        public List<int> testList;
    }
输出结果:




public class LitJsonTest : MonoBehaviour 
{
    void OnGUI()
    {
        int y = 10;
        GUI.Label(new Rect(10,y,1000,30),strJson);
        y += 30;

        if( GUI.Button(new Rect(10,y,100,30),"StrToJson"))
        {
            StringToJson(strJson);
        }
        y += 30;

        if (GUI.Button(new Rect(10, y, 100, 30), "ClassToJson"))
        {
            ClassToJson();
        }
        y += 30;
        GUI.Label(new Rect(10, y, 1000, 30), PJsonStr);
        y += 30;
    }

    string strJson = "{'name':'testName','id':10,'items':[{'itemid':1001,'itemname':'hello'},{'itemid':1002,'itemname':'hello2'}]}";
    void StringToJson(string str)
    {
        JsonData jd = JsonMapper.ToObject(str);

        string name = (string)jd["name"];
        long id = (long)jd["id"];

        int itemCnt = jd["items"].Count;

        Debug.Log("name:" + name);
        Debug.Log("id:" + id);
        Debug.Log("itemCnt:" + itemCnt);

        for (int i = 0; i < itemCnt; i++)
        {
            JsonData jdItem = jd["items"][i];

            int itemid = (int)jdItem["itemid"];
            string itemName = (string)jdItem["itemname"];

            Debug.Log(itemid + ":" + itemName);
        }      
    }
}


1.StringToJson输出结果

Unity3D LitJson 使用方法_第1张图片


你可能感兴趣的:(litjson)