準備好dll檔,新增寫檔用的Script就可以開始了。
使用LitJSON要將資料轉換成JSON格式時,是使用JsonMapper.ToJson()函式來處理,帶入的變數型別是Object。
所以首先需要建立類別,例如說:
public class Character{ public string name; public string job; public bool state; public int itemCount; public Character(string name, string job, bool state, int itemCount) { this.name = name; this.job = job; this.state = state; this.itemCount = itemCount; } }這是一個角色類別,含有name、job、state、itemCount等變數,實作時可以設定值,使用JsonMapper.ToJson()轉換後就會分別是JSON檔內的鍵值和數值。
準備好要寫的資料後,接著就是格式轉換和存檔:
using UnityEngine; using System.Collections; using System.IO; using LitJson; public class JSONWriteTest : MonoBehaviour { void Start(){ Character character = new Character("Tim", "Archer", true, 3); JsonData jsonData; jsonData = JsonMapper.ToJson(character); File.WriteAllText(Application.dataPath + "/JSONWriteTest/JSONWrite.json", jsonData.ToString()); } public class Character{ public string name; public string job; public bool state; public int itemCount; public Character(string name, string job, bool state, int itemCount) { this.name = name; this.job = job; this.state = state; this.itemCount = itemCount; } } }宣告Character物件,設定好變數數值,透過JsonData將轉換成JSON格式的character存起來後,使用File.WriteAllText存到指定路徑上就完成了,另外要注意的是jsonData要轉換成字串。
以下是含有陣列的情況:
using UnityEngine; using System.Collections; using System.IO; using LitJson; public class JSONWriteTest : MonoBehaviour { void Start(){ string[] items = { "Bow", "Arrow", "Bottle" }; Character character = new Character("Tim", "Archer", true, 3, items); JsonData jsonData; jsonData = JsonMapper.ToJson(character); File.WriteAllText(Application.dataPath + "/JSONWriteTest/JSONWrite.json", jsonData.ToString()); } public class Character { public string name; public string job; public bool state; public int itemCount; public string [] items; public Character(string name, string job, bool state, int itemCount, string [] items) { this.name = name; this.job = job; this.state = state; this.itemCount = itemCount; this.items = new string[itemCount]; for (int i = 0; i < itemCount; i++) this.items[i] = items[i]; } } }
最後來提縮排的方法,上圖可以看到轉換出來的JSON檔是一行寫到底的,不好讀也不好修改,所以針對轉換JSON的地方做調整:
void Start() { . . . JsonWriter jsonWriter = new JsonWriter(); jsonWriter.PrettyPrint = true; jsonWriter.IndentValue = 4; JsonMapper.ToJson(character, jsonWriter); File.WriteAllText(Application.dataPath + "/JSONWriteTest/JSONWrite.json", jsonWriter.ToString()); }將前面使用的JsonData換成JsonWriter,JsonWriter可以決定要不要排版及縮排多少,寫檔的地方就和原先的相同,縮排後的結果如下:
以上是存檔的部分,後續或許會試試JSON產生器之類的程式,這次就到這裡。
沒有留言:
張貼留言