Unity中生成JSON以及对应的解析方法
发表于2019-01-15
注意:将库脚本或动态库(LitJSON.dll)放置在Assets目录下的Plugins文件夹中,因为plugins文件夹中的脚本会先运行。
代码如下:
using LitJson; //注意引用命名空间 using UnityEngine; public class LitJsonDemo : MonoBehaviour { // Use this for initialization void Start() { //============JSON的生成============================ JsonData data = new JsonData(); data["name"] = "Czhenya"; //生成嵌套结构的json data["info"] = new JsonData(); data["info"]["age"] = 28; data["info"]["sex"] = "男"; string js1= data.ToJson(); Debug.Log(js1); //============使用jsonMapper生成Json================== //此方法使用的前提是有一个玩家类 Player play1 = new Player(); play1.name = "czy"; play1.age = 22; play1.sex = "男"; string js2 = JsonMapper.ToJson(play1); Debug.Log(js2); //============使用JsonWritter生成Json================== JsonWriter js3 = new JsonWriter(); //对象类型的json js3.WriteObjectStart(); js3.WritePropertyName("name"); js3.Write("zhenya"); js3.WritePropertyName("age"); js3.Write("30"); js3.WritePropertyName("sex"); js3.Write("女"); js3.WriteObjectEnd(); Debug.Log(js3.ToString()); JsonWriter js4 = new JsonWriter(); //生成数组型json js4.WriteArrayStart(); js4.Write("CZHENYA"); js4.Write("25"); js4.Write("男"); js4.WriteArrayEnd(); Debug.Log(js4.ToString()); //需要注意的是有开始就要写结束 JsonWriter js5 = new JsonWriter(); //生成数组含对象 js5.WriteArrayStart(); //第一个对象 js5.WriteObjectStart(); js5.WritePropertyName("name"); js5.Write("zhenya"); js5.WritePropertyName("age"); js5.Write("30"); js5.WritePropertyName("sex"); js5.Write("女"); js5.WriteObjectEnd(); //第二个对象 js5.WriteObjectStart(); js5.WritePropertyName("name"); js5.Write("CZHENYA"); js5.WritePropertyName("AGE"); js5.Write("30"); js5.WritePropertyName("SEX"); js5.Write("男"); js5.WriteObjectEnd(); js5.WriteArrayEnd(); Debug.Log(js5.ToString()); //==========解析JSON 上面创建的Json1================ JsonData jsdata1 = JsonMapper.ToObject(js1); Debug.Log("解析json1 "+jsdata1["name"]+" "+jsdata1["info"]["age"]+""); //遍历JsonData的key由于JsonData实现了IDictionary接口,所以可以使用Foreach进行遍历 IDictionary dic = jsdata1 as IDictionary; foreach (string item in dic.Keys) { Debug.Log(item); } //===========解析上面的js2==================== Player play2 = JsonMapper.ToObject<Player>(js2); Debug.Log("解析js2 " + play2.name + " " + play2.age); //===========解析上面的js3,js4,js5 转换成字符串 js3为例==================== string json3 = js3.ToString(); JsonData jsdata3 = JsonMapper.ToObject(json3); Debug.Log("解析js3 "+jsdata3["name"]+jsdata3["age"]+jsdata3["sex"]); } //玩家类 public class Player { public string name { get; set; } public int age { get; set; } public string sex { get; set; } } }
上述代码结果: