U3D技术采集

Unity解析JSON

2017-01-18  本文已影响17人  游戏开发小Y

1.解析JSON字符串显示字典键值

public void ResolveJson()
    {
                 //定义的JSON字符串,注意JSON的格式
         string str = @"
            {
                ""Name""     : ""yusong"",
                ""Age""      : 26,
                ""Birthday"" : ""1986-11-21"",
                ""Thumbnail"":[
                {
                    ""Url"":    ""http://xuanyusong.com"",
                    ""Height"": 256,
                    ""Width"":  ""200""
                },
                {
                    ""Url"":    ""http://baidu.com"",
                    ""Height"": 1024,
                    ""Width"":  ""500""
                }
 
                ]
            }";
        //这里是解析,包括整形与字符串
        JsonData jd = JsonMapper.ToObject(str);
        Debug.Log("name = " + (string)jd["Name"]);
        Debug.Log("Age = " + (int)jd["Age"]);
        Debug.Log("Birthday = " + (string)jd["Birthday"]);
        JsonData jdItems = jd["Thumbnail"]; 
 
        for (int i = 0; i < jdItems.Count; i++)
        {
            Debug.Log("URL = " + jdItems[i]["Url"]);
            Debug.Log("Height = " + (int)jdItems[i]["Height"]);
            Debug.Log("Width = " + jdItems[i]["Width"]);
        }
    }

2.合成JSON字符串,先合成 然后在输出。

public void MergerJson()
    {
        StringBuilder sb = new StringBuilder ();
        JsonWriter writer = new JsonWriter (sb);
 
        writer.WriteObjectStart ();
 
        writer.WritePropertyName ("Name");
        writer.Write ("yusong");
 
        writer.WritePropertyName ("Age");
        writer.Write (26);
 
        writer.WritePropertyName ("Girl");
 
        writer.WriteArrayStart ();
 
        writer.WriteObjectStart();
        writer.WritePropertyName("name");
        writer.Write("ruoruo");
        writer.WritePropertyName("age");
        writer.Write(24);
        writer.WriteObjectEnd ();
 
        writer.WriteObjectStart();
        writer.WritePropertyName("name");
        writer.Write("momo");
        writer.WritePropertyName("age");
        writer.Write(26);
        writer.WriteObjectEnd ();
 
        writer.WriteArrayEnd();
 
        writer.WriteObjectEnd ();
        Debug.Log(sb.ToString ());
 
        JsonData jd = JsonMapper.ToObject(sb.ToString ());
        Debug.Log("name = " + (string)jd["Name"]);
        Debug.Log("Age = " + (int)jd["Age"]);
        JsonData jdItems = jd["Girl"];
        for (int i = 0; i < jdItems.Count; i++)
        {
            Debug.Log("Girl name = " + jdItems[i]["name"]);
            Debug.Log("Girl age = " + (int)jdItems[i]["age"]);
        }
    }

工程下载: http://vdisk.weibo.com/s/jkBml

上一篇下一篇

猜你喜欢

热点阅读