UnityでJsonUtilityを使用してJsonを解析する



Parsing Json Using Jsonutility Unity



まず、Jsonファイルを記述します。構文はここで参照できます
http://www.runoob.com/json/json-tutorial.html

例:




UTF-8形式で保存することを忘れないでください(そうしないと、中国語のデータが文字化けします)

モデルクラス:



using System.Collections.Generic using System.IO using System [Serializable] public class MainJson { public string ResourcePath public int ProjectNumber public string PictureFormat public List Categories } [Serializable] public class CategoriesGroup { public string name public string intro }

json文字列の名前はC#と一致している必要があることに注意してください

Jsonファイルをロードします。

public static MainJson LoadJsonFromFile() { // json file storage address if (!File.Exists(Application.dataPath + '/StreamingAssets/ListInit.json')) { return null } StreamReader sr = new StreamReader(Application.dataPath + '/StreamingAssets/ListInit.json') // deserialize if (sr == null) { return null } string json = sr.ReadToEnd() if (json.Length > 0) { return JsonUtility.FromJson(json) } return null }

StreamingAsssetsフォルダーに入れて、プロジェクトのエクスポートを容易にし、Jsonファイルを変更します



必要に応じてjsonデータを取得します。

private MainJson status private int maxNumber private string resourcePath private string intros private string pictureFormat private void Awake() { GetJson() } public void GetJson() { status = MainGrid.LoadJsonFromFile() // Get the data in json maxNumber = status.ProjectNumber Debug.Log(maxNumber) resourcePath = status.ResourcePath Debug.Log(resourcePath) pictureFormat = status.PictureFormat Debug.Log(pictureFormat) Debug.Log(status.Categories[2].name) }