引入LitJson(using LitJson;)
下载地址 链接:百度云 密码:vj41
解析Json
LitJson.JsonData result = LitJson.JsonMapper.ToObject(_string); string code = string.Empty; string msg = string.Empty; code = result["code"].ToString(); msg = result["msg"].ToString(); if (!msg.Equals("Success")) { return; } /* { "code": "000", "msg": "Success", "datas": [ { "usr_idx": "147", "usr_nm": "Gㅊㅎㅎㅎㅎ", "thumbnail": "http://media.87870.com/?url=http://images.87870.com/usr/8d5e95147/f5461a6fc2e6100e750cea7bc5edaff1.png&w=512&h=512&a=aspect-cut", "score": "100", "ranking": "1" }, { "usr_idx": "147", "usr_nm": "Gㅊㅎㅎㅎㅎ", "thumbnail": "http://images.87870.com/usr/8d5e95147/f5461a6fc2e6100e750cea7bc5edaff1.png", "score": "100", "ranking": "1" }, { "usr_idx": "2", "usr_nm": "yyy", "thumbnail": "http://images.87870.com/usr/c81e722/eec145d695d1ac700add10a709b79274.png", "score": "10", "ranking": "2" } ] } */ LitJson.JsonData dataItems = result["datas"]; rankingList.Clear(); for (int i = 0; i < dataItems.Count; i++) { RankingUserInfo rankingUserInfo = new RankingUserInfo(); rankingUserInfo.usr_idx = dataItems[i]["usr_idx"].ToString(); rankingUserInfo.usr_nm = dataItems[i]["usr_nm"].ToString(); rankingUserInfo.thumbnail = dataItems[i]["thumbnail"].ToString(); rankingUserInfo.score = dataItems[i]["score"].ToString(); rankingUserInfo.ranking = dataItems[i]["ranking"].ToString(); if (!rankingList.Contains(rankingUserInfo)) rankingList.Add(rankingUserInfo); rankingUserInfo = null; } DebugRankingList();
可以在元素被解析出来后,放入类元素内存储.备用.
生成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"]); } }