Json的使用(二)UnityJson和LitJson的使用

一、UnityJson(Unity引擎自带)

1.文本转Json

//(item文本信息)

JsonUtility.ToJson(item));

2.读取Json文件

//转化的类型,(jsonTex)Json文件

JsonUtility.FromJson<InFo__>(jsonTxt);

二、LitJson(借鉴大神)

1.下载LitJson.dll文件(https://github.com/okamura0510/LitJsonRuler/blob/master/Assets/LJR/Plugins/LitJson.dll)到Assets/Plugins下

2.解析

//解析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"]);

 

}

 

}
3.合成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"]);
}
}

 

转载于:https://www.cnblogs.com/Damon-3707/p/11431197.html

你可能感兴趣的:(json,游戏)