チラ裏Unity

主にUnityについての備忘録ですが誰か様の為になれば

UnityでJSONファイルを読み込む (LitJSON)

開発環境

  • OS X 10.6.8
  • Unity 4.6.0

 

LitJSONのインストール

  1. http://lbv.github.io/litjson/にアクセス
  2. LitJson.dllをダウンロードしてUnityプロジェクトのAssets/Pluginsにコピー

 

パースするJSONファイルの作成

  1. Assets/Resources/JSONディレクトリを作成
  2. 1.で作成したディレクトリに以下の内容でSample.jsonを作成
    {
        "name": "foo",
        "age": 24,
        "weight": 55.8,
        "married": true,
        "birthday": "1990-08-30 03:38:13",
        "friends": [
            {
                "name": "bar",
                "age": 25,
                "weight": 50.2,
                "married": false,
                "birthday": "1989-04-01 15:02:47"
            }
        ]
    }

 

LitJSONでパースしてデシリアライズ

http://lbv.github.io/litjson/docs/quickstart.htmlも参考に

以下のスクリプトを作成して適当なGameObjectにコンポーネントとしてアタッチ

using UnityEngine;
using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;

public class LitJsonSample : MonoBehaviour {

    void Start () {
        TextAsset json = Resources.Load("JSON/Sample"as TextAsset;
        Person person = JsonMapper.ToObject<Person>(json.text);
    }
}

public class Person {
    public string name;
    public int age;
    public double weight;
    public bool married;
    public DateTime birthday;
    public List<Personfriends;
}

 

補足

  • weightでfloat型が使えなかったためdouble型にしています
    JsonException: Can't assign value '55.8' (type System.Double) to type System.Single
  • githubで管理されているリポジトリのREADME.mdによるとライセンスはUnlicense (public domain)なので手軽に使いやすい