本文章由cartzhang編寫,轉載請注明出處。 所有權利保留。
文章鏈接:[http://blog.csdn.net/cartzhang/article/details/50373558](http://blog.csdn.net/cartzhang/article/details/50373558)
作者:cartzhang
### Unity的Json解析<一>–讀取Json文件
因為需要做一個外部文件配置,考慮了XML和Json,而5.3版本對Json做了更新,所以就嘗試一下。
版本更新的Json部分介紹哦:[ [Unity5.3版本更新的Json部分 ]](#)
### Json的在線編輯
Json parser :[http://json.parser.online.fr/](http://json.parser.online.fr/)
Json在線編輯:[http://www.kjson.com/jsoneditor/?f=1](http://www.kjson.com/jsoneditor/?f=1)
第二個是可以直接下載保存到本地的,此操作甚好啊!
### JsonUtility
先看看,在Unity中,我們在其Json工具類中,可用的函數,總共就5個,好少啊!不過,simple is better.
~~~
#region 程序集 UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// H:\Unity\Project\JsonReadTest\Library\UnityAssemblies\UnityEngine.dll
#endregion
using System;
namespace UnityEngine
{
//
// 摘要:
// ///
// Utility functions for working with JSON data.
// ///
public static class JsonUtility
{
//
// 摘要:
// ///
// Create an object from its JSON representation.
// ///
//
// 參數:
// json:
// The JSON representation of the object.
//
// type:
// The type of object represented by the JSON.
//
// 返回結果:
// ///
// An instance of the object.
// ///
[WrapperlessIcall]
public static object FromJson(string json, Type type);
public static T FromJson<T>(string json);
//
// 摘要:
// ///
// Overwrite data in an object by reading from its JSON representation.
// ///
//
// 參數:
// json:
// The JSON representation of the object.
//
// objectToOverwrite:
// The object that should be overwritten.
[WrapperlessIcall]
public static void FromJsonOverwrite(string json, object objectToOverwrite);
//
// 摘要:
// ///
// Generate a JSON representation of the public fields of an object.
// ///
//
// 參數:
// obj:
// The object to convert to JSON form.
//
// prettyPrint:
// If true, format the output for readability. If false, format the output for minimum
// size. Default is false.
//
// 返回結果:
// ///
// The object's data in JSON format.
// ///
public static string ToJson(object obj);
//
// 摘要:
// ///
// Generate a JSON representation of the public fields of an object.
// ///
//
// 參數:
// obj:
// The object to convert to JSON form.
//
// prettyPrint:
// If true, format the output for readability. If false, format the output for minimum
// size. Default is false.
//
// 返回結果:
// ///
// The object's data in JSON format.
// ///
[WrapperlessIcall]
public static string ToJson(object obj, bool prettyPrint);
}
}
~~~
可以看到,主要就是創建對象的和變成Json格式的兩個類型。
### 準備工作
我們需要一個Json文件,這是主角啊,就是要讀取其內容啊。
好了。我隨便寫了個,命名為Test.json放到了我的.\Assets\Resources\目錄下;
Json文件內容如下:
~~~
{"gameName":"JSON Serializer Test","version":"1.0","isStereo":"false","isUseHardWare":"true","statusList":[{"name":"test","id":"1u702"}]}
~~~
### 創建對象類
首先,我們需要創建一個對象類,用來存放從Json文本中讀取的內容。
給這個類命名為GameStatus.cs
~~~
using UnityEngine;
using System;
using System.Collections;
[Serializable]
public class GameStatus
{
public string gameName;
public string version;
public bool isStereo;
public bool isUseHardWare;
public refencenes[] statusList;
}
[Serializable]
public class refencenes
{
public string name;
public int id;
}
~~~
### 需要一個讀取類
這個寫了一個靜態類,以后也可添加寫的內容
名字為LoadJson.cs
~~~
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class LoadJson : MonoBehaviour
{
public static GameStatus LoadJsonFromFile()
{
BinaryFormatter bf = new BinaryFormatter();
if (!File.Exists(Application.dataPath + "/Resources/Test.json"))
{
return null;
}
StreamReader sr = new StreamReader(Application.dataPath + "/Resources/Test.json");
//FileStream file = File.Open(Application.dataPath + "/Test.json", FileMode.Open, FileAccess.ReadWrite);
//if (file.Length == 0)
//{
// return null;
//}
//string json = (string)bf.Deserialize(file);
//file.Close();
if (sr == null)
{
return null;
}
string json = sr.ReadToEnd();
if (json.Length > 0)
{
return JsonUtility.FromJson<GameStatus>(json);
}
return null;
}
}
~~~
說明:代碼被注釋掉的部分,是從網上找的,解析Json為二進制格式,然后在反序列化為字符串,結果,可能是編碼格式問題,不能正確的反序列化,總是報錯。
我表示無奈,只好從寫實使用了StreamReader來處理。
### 調用
調用蠻簡單的,就是在Update中,使用L鍵來加載Json文件。
代碼如下:
~~~
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class ReadJson : MonoBehaviour
{
void Update()
{
if(Input.GetKeyDown(KeyCode.S))
{
//Save();
}
if (Input.GetKeyDown(KeyCode.L))
{
GameStatus status = LoadJson.LoadJsonFromFile();
Debug.Log(status);
}
}
}
~~~
### 測試結果
在場景中,建立一個空對象,然后把ReadJson拖拽到對象上,運行,按下L鍵,就可以使用斷點查看,當然也后Log輸出。
結果如下圖:


### 說明
總體過程都很簡單。工程就不一一上傳。
若有問題,請隨時聯系!
非常感謝!
- 前言
- Unity隨機Prefab,自動前往某點處理
- Unity導入FBX自動進行動畫切分
- Unity5中的粒子縮放(附測試源碼)
- Unity和虛幻的比較
- Unity 實現Log實時輸出到屏幕或控制臺上&lt;一&gt;
- Unity 實現Log實時輸出到屏幕或控制臺上&lt;二&gt;
- Unity的Json解析<一>--讀取Json文件
- Unity的Json解析<二>–寫Json文件
- Unity 的OCulus VR開發遇到的坑---OC版本差異
- Unity中一鍵創建常用文件夾
- Unity版本與虛擬現實頭盔Deepoon大朋版本測試
- Unity 多場景打包
- Untiy中的數據平滑處理
- Unity中SendMessage和Delegate效率比較