【Json】SimpleJson在项目中的使用

具体代码可以查看:http://wiki.unity3d.com/index.php/SimpleJSON

推荐一个很好用的 json 解析网站 :http://www.bejson.com/

使用SimpleJson 只需要把脚本导入即可


解析Json 用WWW 读取路径 或者服务器 发送过来 声明var 变量 去承接 

JSON.Parse(string json) 参数是一个string 类型

Parse:j就是解析的意思

private void RectPostMsg (string json)
	{
		var N = JSON.Parse (json);
		string msg = N ["Message"];
		if (msg == "004") {
			UIManager.GetInstance ().ShowMessageBox ("园所码错误!");
			return;
		}
		if (msg == "OK") {
			string val = N ["Data"] ["OrganId"]; 

			Debug.Log ("RectPostMsgOK:" + val);

			
		}

	}



其中 这个 json 是以{ } 括号开头的 所以 直接用 N【XXX】【XXX】可以 获取 如果 要是以 [ ]  开头怎么办呢? 

public IEnumerator LoadJson ()
	{
		WWW www = new WWW ("file:///" + Application.persistentDataPath + "/myjson.json");
		yield return www;
		if (www.error != null) {
			Debug.Log ("UIUpload1 error:" + www.error);
		} else if (www.isDone) {
			Debug.Log ("UIUpload1 isDone:" + www.text);
			my_Json = www.text;
			jsonData = JSON.Parse (my_Json);
		}
	}

同样也是WWW读取过来 用JSONParse解析

只不过用的是jsonData 来承接  private JSONNode jsonData; 是一个JSONNode 类型

[
    {
        "id": "2",
        "attribute": [
            {
                "number": "0",
                "bl_Default": "false",
                "bl_Active": "true",
                "alpha": "1.0",
                "bl_InterAble": "true"
            },
            {
                "number": "1",
                "bl_Default": "true",
                "bl_Active": "false",
                "alpha": "0.0",
                "bl_InterAble": "false"
            }
        ]
    }
]

解析的是一个[ ] 开头的json 

想得到这个value j就要这样写 jsonData [0] ["id"].Value   因为是以[ ] 开头表明就是一个数组 因为json 本身就是 数组套字典 

要是合并起来的话 也是一样的

[
    {
        "id": "1",
        "attribute": [
            {
                "number": "0",
                "bl_Default": "False",
                "bl_Active": "True",
                "alpha": "1",
                "bl_InterAble": "True"
            },
            {
                "number": "1",
                "bl_Default": "False",
                "bl_Active": "True",
                "alpha": "1",
                "bl_InterAble": "True"
            }
        ]
    },
    {
        "id": "1",
        "attribute": [
            {
                "number": "0",
                "bl_Default": "False",
                "bl_Active": "True",
                "alpha": "1",
                "bl_InterAble": "True"
            },
            {
                "number": "1",
                "bl_Default": "False",
                "bl_Active": "True",
                "alpha": "1",
                "bl_InterAble": "True"
            }
        ]
    },
    {
        "id": "2",
        "attribute": [
            {
                "number": "0",
                "bl_Default": "False",
                "bl_Active": "True",
                "alpha": "1",
                "bl_InterAble": "True"
            },
            {
                "number": "1",
                "bl_Default": "True",
                "bl_Active": "False",
                "alpha": "0",
                "bl_InterAble": "False"
            }
        ]
    }
]

下面附上 项目中的使用过程 合并json 解析json


using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using WhtGame;
using cn.sharesdk.unity3d;
using EasyAR;
using System.IO;
using DG.Tweening;
using System.Xml;
using System.Collections.Generic;
using System;
using SimpleJSON;

public class UIUpload1 : UIBaseWindow
{

	public UnityEngine.UI.RawImage ui_BG;
	public UnityEngine.UI.RawImage ui_BG_1;

	[HideInInspector]
	public bool isPicLoop;
	private string filename;
	private string temp;
	private int index = 0;
	private float waitTime = 2.2f;
	private Texture temp_Texture;
	private int int_FileChild = 0;
	DirectoryInfo dirInfo;
	private string default_Path;

	public Upload_UI[] uipload;
	public GameObject[] ui_Start;


	private string json_Path;
	private int default_Number = 0;
	private int active_Number = 0;
	private int alpha_Num = 0;
	private int interable_Num = 0;

	//Json
	public JsonInfo jsonInfo;
	private string my_Json;
	private JSONNode jsonData;
	private int json_ID = 0;
	private bool hasId;
	private int index_Jndex = 0;
	public bool isLoadJsonInfo = true;

	void Awake ()
	{


		# if UNITY_EDITOR
		//		mySprite_Path = "file://" + Application.streamingAssetsPath + "/";
		//		temp = "/StreamingAssets/ScreenShot/";
		filename = "file:///" + Application.persistentDataPath + "/ScreenShot/";
		default_Path = Application.persistentDataPath + "/ScreenShot/";

		# else

		#if UNITY_ANDROID

		temp = "/ScreenShot/";
		filename = "file://" + Application.persistentDataPath + temp;
		default_Path = Application.persistentDataPath + temp;
		#endif

		#if UNITY_IPHONE
		temp = "/Raw/ScreenShot/";
		filename = "file://"+ Application.temporaryCachePath + temp;
		default_Path = Application.temporaryCachePath + temp;
		#endif

		#if UNITY_STANDALONE_WIN
		filename = "Screenshot.png";
		#endif
		#endif

		//XML
		# if UNITY_EDITOR
		json_Path = Application.persistentDataPath + @"/myJson.json";
		# else

		#if UNITY_ANDROID

		json_Path = "file://" + Application.persistentDataPath + @"/myJson.json";
		#endif

		#if UNITY_IPHONE
		json_Path = "file://"+ Application.temporaryCachePath + @"/myJson.json";
		#endif
		#endif


		BtnOnClick ("UIUpload1_UPdataBtn", this.OnClick);
		BtnOnClick ("UIUpload1_MsgBtn", this.OnClick);
		BtnOnClick ("UIUpload1_ScanBtn", this.OnClick);
		BtnOnClick ("UIUpload1_PlayBtn", this.OnClick);
		BtnOnClick ("UIUpload1_WatchBtn", this.OnClick);

		jsonInfo = new JsonInfo ();
		//		jsonInfo.attribute = new JsonAttribute[2];
		jsonInfo.Init ();
	}

	void Update ()
	{
		if (isPicLoop) {
			if (int_FileChild != 0) {
				waitTime += Time.deltaTime;
				if (waitTime > 2.2f) {
					waitTime = 0;
					index++;
					if (index >= int_FileChild + 1) {
						index = 1;
					}
					StartCoroutine (LoadPicture (index));
				}
			}
		}
	}

	IEnumerator LoadPicture (int index)
	{
		//WWW www = new WWW(mySprite_Path + myDataAll[index].Image);

		WWW www = new WWW (filename + index + ".jpg");
		//		Debug.Log ("加载图片的路径" + www.url);
		yield return www;

		if (www.error != null) {
			Debug.Log (www.error);
		} else if (www.isDone) {

			temp_Texture = www.texture;
			ChangeSprite ();
		}
	}

	public void ChangeSprite ()
	{
		ui_BG.gameObject.SetActive (false);
		ui_BG_1.texture = temp_Texture;
	}

	public int GetFileChild ()
	{
		dirInfo = new DirectoryInfo (default_Path);

		if (dirInfo.Exists == false) {
			return int_FileChild = 0;
		}

		foreach (FileInfo item in dirInfo.GetFiles("*.jpg")) {
			//			print (item.Extension);
			int_FileChild++;
		}
		return int_FileChild;
	}


	public override void OnUIShow ()
	{
		isPicLoop = true;
		int_FileChild = 0;

		GetFileChild ();
		isLoadJsonInfo = true;
		LoadInfoManager ();
		Debug.Log (UIManager.GetInstance ().getId);
	}


	private void OnClick (GameObject go)
	{
		isPicLoop = false;
		//在这里监听按钮的点击事件
		//提交按钮
		if (go.name == "UIUpload1_UPdataBtn") {
			//				UIManager.GetInstance ().ShowWindow (WindowID.WindowID_ARCreat);
			CreateJson (0);
			UIManager.GetInstance ().ShowWindow (WindowID.WindowID_Upload2);
			UIManager.GetInstance ().HideWindow (WindowID.WindowID_Upload1);
			Debug.Log ("Show UIUpload2");
		} 
		/*
		else if (go.name == "UploadBackButton") {
			UIManager.GetInstance ().HideWindow (WindowID.WindowID_Upload1);
			UIManager.GetInstance ().ShowWindow (WindowID.WindowID_AR);	
			UIManager.GetInstance ().ShowWindow (WindowID.WindowID_UIMainMenu);
		}
		*/
		if (go.name == "UIUpload1_MsgBtn") {
			//			UIManager.GetInstance ().ShowWindow (WindowID.WindowID_UISideLine);
			UIManager.GetInstance ().ShowWindow (WindowID.WindowID_AR);
			UIManager.GetInstance ().HideWindow (WindowID.WindowID_Upload1);
			UIManager.GetInstance ().ShowWindow (WindowID.WindowID_UIMainMenu);
			Debug.Log ("Show UIUpload2");
		}
		if (go.name == "UIUpload1_ScanBtn") {
			ARBuilder.Instance.CameraDeviceBehaviours [0].OpenAndStart ();
			UIManager.GetInstance ().HideWindow (WindowID.WindowID_Home);
			UIManager.GetInstance ().HideWindow (WindowID.WindowID_AR);
			UIManager.GetInstance ().HideWindow (WindowID.WindowID_Upload1);
			UIManager.GetInstance ().HideWindow (WindowID.WindowID_UIMainMenu);
			UIManager.GetInstance ().ShowWindow (WindowID.WindowID_UIScreen);

		}
		//play 按钮
		if (go.name == "UIUpload1_PlayBtn") {
		}
		//观看获奖作品动画
		if (go.name == "UIUpload1_WatchBtn") {
			CreateJson (1);
		}
	}

	//显示可提交 等 UI模块
	public void CreateJson (int index)
	{

		uipload [index].text_OBJ [0].SetActive (false);
		uipload [index].text_OBJ [1].SetActive (true);
		//		DOTween.ToAlpha (() => uipload [index].image_UI.color, x => uipload [index].image_UI.color = x, 1, 0f);
		uipload [index].image_UI.color = new Color (1, 1, 1, 1);
		uipload [index].btn_OBJ.interactable = true;

		//如果不存在这个路径(说明第一次创建)
		if (!File.Exists (json_Path)) {
			jsonInfo.id = UIManager.GetInstance ().getId;
			jsonInfo.attribute [0].bl_Default = uipload [0].text_OBJ [0].activeInHierarchy;
			jsonInfo.attribute [0].bl_Active = uipload [0].text_OBJ [1].activeInHierarchy;
			jsonInfo.attribute [0].alpha = uipload [0].image_UI.color.a;
			jsonInfo.attribute [0].bl_InterAble = uipload [0].btn_OBJ.interactable;
			SaveMyJson (jsonInfo);
		}
		//如果存在这个路径 判断id 是否存在 如果存在则更新数值 如果不存在则添加新的json
		else {
			StartCoroutine (LoadJson ());
			if (isLoadJsonInfo) {
				LoadHasId ();
			} else {
				HasIDInfo ();
			}
		}
	}

	public IEnumerator LoadJson ()
	{
		WWW www = new WWW ("file:///" + Application.persistentDataPath + "/myjson.json");
		yield return www;
		if (www.error != null) {
			Debug.Log ("UIUpload1 error:" + www.error);
		} else if (www.isDone) {
			Debug.Log ("UIUpload1 isDone:" + www.text);
			my_Json = www.text;
			jsonData = JSON.Parse (my_Json);
		}
		StartCoroutine (WaitLoadJsonInfo ());
	}

	public IEnumerator WaitLoadJsonInfo ()
	{
		yield return new WaitForEndOfFrame ();

		if (isLoadJsonInfo) {
			LoadHasId ();
		} else {
			HasIDInfo ();
		}
	}

	public void SaveMyJson (object json)
	{
		Debug.Log (json);
		my_Json = "[" + JsonUtility.ToJson (json) + "]";
		System.IO.File.WriteAllText (Application.persistentDataPath + "/myjson.json", my_Json); 
	}
	//如果ID 相同 则更新  如果ID 不同 则添加json
	public void HasIDInfo ()
	{
		for (int i = 0; i < jsonData.Count; i++) {
			json_ID = Convert.ToInt32 (jsonData [i] ["id"].Value);
			if (json_ID == UIManager.GetInstance ().getId) {
				hasId = true;
				index_Jndex = i;

			} else {
				hasId = false;
			}
		}
		if (hasId) {

			for (int j = 0; j < 2; j++) {
				jsonData [index_Jndex] ["attribute"] [j] ["bl_Default"].Value = uipload [j].text_OBJ [0].activeInHierarchy.ToString ();
				jsonData [index_Jndex] ["attribute"] [j] ["bl_Active"].Value = uipload [j].text_OBJ [1].activeInHierarchy.ToString ();
				jsonData [index_Jndex] ["attribute"] [j] ["alpha"].Value = uipload [j].image_UI.color.a.ToString ();
				jsonData [index_Jndex] ["attribute"] [j] ["bl_InterAble"].Value = uipload [j].btn_OBJ.interactable.ToString ();
			}
			my_Json = jsonData.ToString ();
			System.IO.File.WriteAllText (Application.persistentDataPath + "/myjson.json", my_Json);
			my_Json = null;
			return;
		} else {
			JSONNode json_Temp = new JSONNode ();
			my_Json = jsonData [0].ToString ();
			json_Temp = JSON.Parse (my_Json);
			jsonData.Add ((jsonData.Count - 1).ToString (), json_Temp);
			jsonData [jsonData.Count - 1] ["id"].Value = UIManager.GetInstance ().getId.ToString ();
			for (int j = 0; j < 2; j++) {
				jsonData [jsonData.Count - 1] ["attribute"] [j] ["bl_Default"].Value = uipload [j].text_OBJ [0].activeInHierarchy.ToString ();
				jsonData [jsonData.Count - 1] ["attribute"] [j] ["bl_Active"].Value = uipload [j].text_OBJ [1].activeInHierarchy.ToString ();
				jsonData [jsonData.Count - 1] ["attribute"] [j] ["alpha"].Value = uipload [j].image_UI.color.a.ToString ();
				jsonData [jsonData.Count - 1] ["attribute"] [j] ["bl_InterAble"].Value = uipload [j].btn_OBJ.interactable.ToString ();
			}
			//不同创建新的json
			my_Json = jsonData.ToString ();
			System.IO.File.WriteAllText (Application.persistentDataPath + "/myjson.json", my_Json);
			my_Json = null;
		}
	}

	public void LoadInfoManager ()
	{
		if (File.Exists (json_Path)) {
			StartCoroutine (LoadJson ());
		}
	}
	//加载
	public void LoadHasId ()
	{
		isLoadJsonInfo = false;
		for (int i = 0; i < jsonData.Count; i++) {
			json_ID = Convert.ToInt32 (jsonData [i] ["id"].Value);
			if (json_ID == UIManager.GetInstance ().getId) {
				hasId = true;
				index_Jndex = i;
				break;
			} else {
				hasId = false;
			}
		}
		if (hasId) {
			for (int j = 0; j < 2; j++) {
				uipload [j].text_OBJ [0].SetActive (Convert.ToBoolean (jsonData [index_Jndex] ["attribute"] [j] ["bl_Default"].Value));
				uipload [j].text_OBJ [1].SetActive (Convert.ToBoolean (jsonData [index_Jndex] ["attribute"] [j] ["bl_Active"].Value));
				uipload [j].image_UI.color = new Color (255, 255, 255, Convert.ToSingle (jsonData [index_Jndex] ["attribute"] [j] ["alpha"].Value));
				uipload [j].btn_OBJ.interactable = Convert.ToBoolean (jsonData [index_Jndex] ["attribute"] [j] ["bl_InterAble"].Value);
			}
		} else {
			for (int j = 0; j < 2; j++) {
				uipload [j].text_OBJ [0].SetActive (true);
				uipload [j].text_OBJ [1].SetActive (false);
				uipload [j].image_UI.color = new Color (1, 1, 1, 0);
				uipload [j].btn_OBJ.interactable = false;
			}
		}
	}

	public void InitNumber ()
	{
		default_Number = 1;
		active_Number = 0;
		alpha_Num = 0;
		interable_Num = 0;
	}
}

[System.Serializable]
public class Upload_UI
{
	public GameObject[] text_OBJ;
	public UnityEngine.UI.Image image_UI;
	public Button btn_OBJ;
}

[Serializable]
public class JsonInfo
{
	public int id = 0;
	public JsonAttribute[] attribute = { new JsonAttribute (), new JsonAttribute () };

	public void Init ()
	{
		for (int i = 0; i < 2; i++) {
			attribute [i].number = i;
			attribute [i].bl_Default = true;
			attribute [i].bl_Active = false;
			attribute [i].alpha = 0;
			attribute [i].bl_InterAble = false;
		}
	}
}

[Serializable]
public class JsonAttribute
{
	public int number = 0;
	public bool bl_Default = true;
	public bool bl_Active = false;
	public float alpha = 0;
	public bool bl_InterAble = false;

}




  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unity_阿黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值