開発したアプリなど一覧

Unity で JSON を利用する

アフィリエイトリンクを含む場合があります

サーバとのデータのやりとりを JSON で行おうとしたときのメモ。

Unity で Json を利用するには MiniJSON を使用するのが楽っぽい。C# で書かれており MIT ライセンスなので使いやすいだろう。

Unity3D: MiniJSON Decodes and encodes simple JSON strings. Not intended for use with massive JSON strings, probably < 32k preferred. Handy for parsing JSON from inside Unity3d.

上記よりダウンロードし、 plugins 以下に MiniJSON.cs という名で保存しよう。

JSON を読み込む

さっくり言うと, using MiniJSON; してテキストデータを Json.Deserialize に打ち込めばおkです。それっぽいオブジェクトが返ってきます。

IEnumerator Start () { string url = "http://example.com/test.json"; WWW www = new WWW(url); yield return www; var json = Json.Deserialize(www.text) as IDictionary<string, object>; Debug.Log (www.text); Debug.Log (json["title"]); Debug.Log (json["description"]); }

IDictionary を利用しているので using System.Collections.Generic; も入れておきましょう。

これを実行すると以下のように出力される

{ "title": "hoge", "description": "fuga" } hoge fuga

リスト形式の場合は IList を利用するのが良いのかな。

IEnumerator Start () { string url = "http://example.com/test2.json"; WWW www = new WWW(url); yield return www; Debug.Log (www.text); IList json = (IList)Json.Deserialize(www.text); foreach (IDictionary item in json) { Debug.Log (item["title"]); } }

結果は以下のような感じに

[ { "title": "hoge", "description": "fuga" }, { "title": "foo", "description": "bar" } ] hoge foo

これで読み込みできた。

Sponsored Link

コメント

タイトルとURLをコピーしました