[置顶] Unity中Json创建,解析

       我用的是LitJson.dll,JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。
       Json创建中writer.WriteObjectStart ();就等同于“{”,writer.WriteObjectEnd ()就等同于“}”,最后要转换成string型,json = writer.ToString ();。解析Json时,JsonData jsonData = JsonMapper.ToObject (json);注意复合Json解析完了是一个数组

using UnityEngine;
using System.Collections;
using LitJson;

public class Test : MonoBehaviour {

	string json1;
	string json2;
	string json3;

	string name;
	int lv;
	string job;
	float exp;

	//创建json
	void CteateJson()
	{
		JsonWriter writer = new JsonWriter ();
		writer.WriteObjectStart ();
		writer.WritePropertyName ("name");
		writer.Write ("张三");
		writer.WritePropertyName ("lv");
		writer.Write (1);
		writer.WritePropertyName ("job");
		writer.Write ("法师");
		writer.WritePropertyName ("exp");
		writer.Write (1.1);
		writer.WriteObjectEnd ();

		json1 = writer.ToString ();
		Debug.Log (json1);
	}



	//解析Json
	void ParsingJson()
	{
		JsonData jsonData = JsonMapper.ToObject (json1);

		name = jsonData ["name"].ToString ();
		lv = int.Parse(jsonData["lv"].ToString());
		job = jsonData["job"].ToString();
		exp = float.Parse(jsonData["exp"].ToString());
		Debug.Log ("name:" + name);
	}

	//创建复合Json
	void CreateCompostieJson()
	{
		JsonWriter writer = new JsonWriter ();
		writer.WriteObjectStart ();
		writer.WritePropertyName ("name");
		writer.Write ("李四");
		writer.WritePropertyName ("info");
		writer.WriteObjectStart ();
		writer.WritePropertyName ("lv");
		writer.Write (2);
		writer.WritePropertyName ("job");
		writer.Write ("战士");
		writer.WritePropertyName ("exp");
		writer.Write (2.2);
		writer.WriteObjectEnd ();
		writer.WriteObjectEnd ();

		json2 = writer.ToString ();
		Debug.Log ("json2:" + json2);
	}

	//解析复合Json
	void ParsingCompostieJson()
	{
		JsonData jsonData = JsonMapper.ToObject (json2);
		Debug.Log(jsonData ["name"].ToString ());
		Debug.Log(jsonData ["info"] ["lv"].ToString ());
	}

	//生成Json数组
	void CreatdJsonArray()
	{
		JsonWriter writer = new JsonWriter ();
		writer.WriteArrayStart ();
		writer.Write ("张三");
		writer.Write (1);
		writer.Write ("法师");
		writer.Write (1.1);
		writer.WriteArrayEnd ();

		json3 = writer.ToString ();
		Debug.Log ("json3:" + json3);
	}

	//解析Json数组
	void ParsingJsonArray()
	{
		JsonData jsonData = JsonMapper.ToObject (json3);
		jsonData[0].ToString();
		jsonData[1].ToString();


	}


	void OnGUI()
	{
		if (GUILayout.Button ("创建Json"))
			CteateJson ();
		if (GUILayout.Button ("解析Json"))
			ParsingJson ();
		if (GUILayout.Button ("创建复合Json"))
			CreateCompostieJson ();
		if (GUILayout.Button ("解析复合Json"))
			ParsingCompostieJson ();
		if (GUILayout.Button ("创建Json数组"))
			CreatdJsonArray ();
	}

}


你可能感兴趣的:(json,C#)