具体代码可以查看: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);
}
}
只不过用的是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"
}
]
}
]
想得到这个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"
}
]
}
]
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;
}