牛X的JSON解析JSON字符串显示字典键值
1 public void ResolveJson() 2 { 3 //定义的JSON字符串,注意JSON的格式 4 string str = @” 5 { 6 “”Name”” : “”yusong””, 7 “”Age”” : 26, 8 “”Birthday”” : “”1986-11-21″”, 9 “”Thumbnail””:[ 10 { 11 “”Url””: “”http://xuanyusong.com””, 12 “”Height””: 256, 13 “”Width””: “”200″” 14 }, 15 { 16 “”Url””: “”http://baidu.com””, 17 “”Height””: 1024, 18 “”Width””: “”500″” 19 } 20 21 ] 22 }”; 23 //这里是解析,包括整形与字符串 24 JsonData jd = JsonMapper.ToObject(str); 25 Debug.Log(“name = ” + (string)jd[“Name”]); 26 Debug.Log(“Age = ” + (int)jd[“Age”]); 27 Debug.Log(“Birthday = ” + (string)jd[“Birthday”]); 28 JsonData jdItems = jd[“Thumbnail”]; 29 30 for (int i = 0; i < jdItems.Count; i++) 31 { 32 Debug.Log(“URL = ” + jdItems[i][“Url”]); 33 Debug.Log(“Height = ” + (int)jdItems[i][“Height”]); 34 Debug.Log(“Width = ” + jdItems[i][“Width”]); 35 } 36 } 37 38 //合成JSON字符串,先合成 然后在输出。 39 40 public void MergerJson() 41 { 42 StringBuilder sb = new StringBuilder (); 43 JsonWriter writer = new JsonWriter (sb); 44 45 writer.WriteObjectStart (); 46 47 writer.WritePropertyName (“Name”); 48 writer.Write (“yusong”); 49 50 writer.WritePropertyName (“Age”); 51 writer.Write (26); 52 53 writer.WritePropertyName (“Girl”); 54 55 writer.WriteArrayStart (); 56 57 writer.WriteObjectStart(); 58 writer.WritePropertyName(“name”); 59 writer.Write(“ruoruo”); 60 writer.WritePropertyName(“age”); 61 writer.Write(24); 62 writer.WriteObjectEnd (); 63 64 writer.WriteObjectStart(); 65 writer.WritePropertyName(“name”); 66 writer.Write(“momo”); 67 writer.WritePropertyName(“age”); 68 writer.Write(26); 69 writer.WriteObjectEnd (); 70 71 writer.WriteArrayEnd(); 72 73 writer.WriteObjectEnd (); 74 Debug.Log(sb.ToString ()); 75 76 JsonData jd = JsonMapper.ToObject(sb.ToString ()); 77 Debug.Log(“name = ” + (string)jd[“Name”]); 78 Debug.Log(“Age = ” + (int)jd[“Age”]); 79 JsonData jdItems = jd[“Girl”]; 80 for (int i = 0; i < jdItems.Count; i++) 81 { 82 Debug.Log(“Girl name = ” + jdItems[i][“name”]); 83 Debug.Log(“Girl age = ” + (int)jdItems[i][“age”]); 84 } 85 }