|
XML与JSON在开发中非常重要, 其实核心就是处理字符串。一个是XML的字符串一个是JSON的字符串,尤其是在处理网络请求的时候,肯定是要用的。另外现在JSON非常的流行,我写了一个简单的例子融合了XML与JSON的合成与解析,希望大家喜欢!
http://blog.csdn.net/liulala16/article/details/8679024
首先注意头文件,LitJson是处理JSON的第三方库,最后我会给出下载地址。
[mw_shl_code=csharp,true]
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using LitJson;[/mw_shl_code]
解析JSON字符串显示字典键值[mw_shl_code=csharp,true]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["Url"]);
Debug.Log("Height = " + (int)jdItems["Height"]);
Debug.Log("Width = " + jdItems["Width"]);
}
}[/mw_shl_code]运行结果
6.合成JSON字符串,先合成 然后在输出。
[mw_shl_code=cpp,true]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["name"]);
Debug.Log("Girl age = " + (int)jdItems["age"]);
}
}[/mw_shl_code]
运行结果工程下载:http://vdisk.weibo.com/s/jkBml
|
|