UnityでJSONを扱う
UnityでJSONを使うにはいくつか方法があるようですが、今回はLitJSONを使用しました。
- LitJSON 0.5 をダウンロードして解凍
- UnityのプロジェクトでPluginsフォルダを作って、LitJSONをコピー
- 今回作ったのは「東京電力電力供給状況API」からデータを取得するプログラム。
- @ssciさん、素晴らしいサービスをありがとうございます。
- 次の部分がJsonからオブジェクトを復元する部分です。簡単。
Data[] d = JsonMapper.ToObject<Data[]> (www.text);
電気の供給状況に応じて、明かりが変化するゲームらしきものを作ってみました。
当たり前のように使っていた電気ですが、今回、それがいかに素晴らしいことであるかを認識させられました。
震災の被害に合われた方々が、一刻も早くもとのように生活できることを祈っています。
- Json読み込みソース全体
using UnityEngine; using System.Collections; using System.Collections.Generic; using LitJson; public class DataLoader : MonoBehaviour { /* "saving": false, "hour": 0, "capacity_updated": "2011-03-22 16:05:00", "month": 3, "usage_updated": "2011-03-22 17:05:25", "entryfor": "2011-03-22 15:00:00", "year": 2011, "usage": 2770, "capacity": 3750, "day": 23 */ int firstYear = 2011; int firstMonth = 3; public string url ="http://tepco-usage-api.appspot.com/"; public List<Data> dataList = new List<Data>(); IEnumerator Start () { System.DateTime dtNow = System.DateTime.Now; System.DateTime dtFirst = new System.DateTime(firstYear, firstMonth, 1); while(dtNow >= dtFirst){ string theDate = dtFirst.ToString("yyyy/MM")+".json"; WWW www = new WWW(url+theDate); yield return www; Data[] d = JsonMapper.ToObject<Data[]> (www.text); //Jsonからオブジェクトを復元 System.Array.Reverse(d); dataList.AddRange(d); dtNow = dtNow.AddMonths(-1); } } // Update is called once per frame void Update () { } } [System.Serializable] public class Data { public bool saving; public int hour; public string capacity_updated; public int month; public string usage_updated; public string entryfor; public int year; public int usage; public int capacity; public int day; }