Unity的Json解析--讀取Json檔案
Unity的Json解析<一>–讀取Json檔案
因為需要做一個外部檔案配置,考慮了XML和Json,而5.3版本對Json做了更新,所以就嘗試一下。
版本更新的Json部分介紹哦: [Unity5.3版本更新的Json部分 ]
Json的線上編輯
第二個是可以直接下載儲存到本地的,此操作甚好啊!
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的Json解析--讀取Json檔案
Unity的Json解析<一>–讀取Json檔案 因為需要做一個外部檔案配置,考慮了XML和Json,而5.3版本對Json做了更新,所以就嘗試一下。 版本更新的Json部分介紹哦: [Unity5.3版本更新的Json部分 ]
java讀取json檔案並轉換為String
import java.io.*; public class Output { //測試 public static void main(String[] args){ String json = "null"; try { json = readJsonData("I
C語言讀取JSON檔案
用來讀取json檔案並賦值給物件,使用了cJSON typedef struct { cJSON *url; char path[100]; char app_name[100]; } Enter; int main(){ FILE *
vscode中讀取json檔案settings.json
讀取檔案的內容: 讀取檔案的方法: var settingsPath = process.env.AppData + "\\Code\\User\\settings.json"; var allConfigJson = JSON.parse(fs.readFileSync(set
java 讀取json檔案方法以及操作json物件方法。
1 獲取本地js檔案路徑 Fileuri = ParseTools.class.getClassLoader().getResource("com/zxcl/parsejs/XinZhongChengParse.js").toURI(); 2
Java 自動讀取json檔案轉化為實體類
思路: 1 建立一個輔助類,與json檔案和轉化實體類分別建立對應關係 2 建立輔助類的註解屬性與json檔案屬性對應 3 輔助類欄位屬性與實體類相同 具體需求 json檔案 {"Main": {"TestNo": "30103182222","appliName": "大小
[torchtext]如何利用torchtext讀取json檔案並生成batch
設定Field 首先載入torchtext from torchtext import data 設定Field,對輸入文字資料的格式進行"預設定" question = data.Field(sequential=True, fix_length=20,
js 讀取JSON檔案
json檔案路徑 :url:'/static/register.json', //取得分類資料 var data1 ; $.ajax({ url:
Java解析(讀取)Json資料
以前看過書上說,XML是web service間傳輸資訊的標準格式吧,就看了看XML。最近在做個網站,又說是有了JSON,第一回聽說就看了看,總結總結一下。 1.JSON介紹 JSON比XML簡單,主要體現在傳輸相同資訊的情況下,檔案的大小不同。 JSON只用於傳輸資訊,
C++使用jsoncpp讀取json檔案
我用的是VS2015,相關程式碼與資源https://download.csdn.net/download/ll596214569/10870532 首先,建立一個資料夾用來存放整個工程以及jsoncpp的程式碼和json檔案 其中jsoncpp-src-0.5.
iOS-解析讀取CSV檔案,解析excel檔案
專案中可能會遇到資料庫中匯出CSV格式資料,類似於如下圖: 需要將csv資料匯入程序序中使用,或者寫入本地資料庫檔案中. *什麼是CSV? CSV,即逗號分隔值(Comma-Separ
ResourceUtils無法讀取json檔案
應用場景 springboot maven專案 問題 在使用spring的 ResourceUtils.getFile(""); 獲取字尾為 json 的檔案時一直提示檔案不存在。覺得很奇怪,換
Unity的Json解析–寫Json檔案
Unity的Json解析<二>–寫Json檔案 本章對Json的寫檔案,做個處理. 寫檔案也非常簡單,把大象裝冰箱一樣,分三步, 建立檔案, 把內容寫入檔案, 然後關閉檔案. 內容 我們要處理的是所寫的內容,我們打算寫什
【node學習】koa2搭建簡單的伺服器,讀取json檔案開啟圖表專案
需求:用koa2搭建一個簡單的伺服器,能夠讀取json檔案開啟echarts圖表專案。我們知道,不能直接開啟圖表檔案,可以使用hbuilder這種自帶內建伺服器的編輯器,或者vscode的live-server外掛開啟。如果不想在電腦上下載很多編輯器,可以手動用node搭建一個。 1.安裝k
PHP讀取Json檔案
1.data.json檔案 { "goods":[ { "type"
大資料實時計算Spark學習筆記(9)—— Spar SQL(1) 讀取 json 檔案
1 Spark SQL 程式設計方式:(1)SQL;(2) DataFrame API scala> case class Customer(id:Int,name:String,age:Int) defined class Customer scala&g
C++ 讀取json檔案內容
int main(int argc, const char* argv[]){//Options opts;//try {//int exitCode = parseCommandLine(argc, argv, &opts);//if (exitCode != 0)
React Native 之讀取JSON 檔案
一:建立json 檔案 放在 ./data/目錄下 { "employees": [ { "FamilyName": "張", "giveName": "三", "salar
python讀取json檔案
json檔案如下: [{ “fontFamily”: “微軟雅黑”, “fontSize”: 12, “BaseSettings”:{ “font”:1, “size”:2 } } { “fontFamily”: “微黑”, “fontSize”: 22, “BaseSettings”:{
解析本地json檔案,模擬網路請求
/** * Demo class * * @author yyd * @date 2017/11/15 */ public class ParseLocalJsonUtil { /** * 從asset路徑下讀取對應檔案轉String輸出 * <p&