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
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者