万年素人からHackerへの道

万年素人がHackerになれるまで殴り書きするぜ。

Unity C# JsonUtility

Unity - マニュアル: JSON 形式にシリアライズ

今更ながらJsonUtility

using UnityEngine;
using System.Collections;

public class JsonTest : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {
        MyClass myObject = new MyClass ();
        myObject.level = 1;
        myObject.timeElapsed = 47.5f;
        myObject.playerName = "Dr Charles Francis"; 

        string json = JsonUtility.ToJson (myObject);
        Debug.Log (json);

        var myObject2 = JsonUtility.FromJson<MyClass> (json);
        Debug.Log (myObject2.level);
        Debug.Log (myObject2.timeElapsed);
        Debug.Log (myObject2.playerName);

        var jsonStr = "{\"level\":1,\"timeElapsed\":47.5,\"playerName\":\"Dr Charles Francis\"}";
        var myObject3 = JsonUtility.FromJson<MyClass> (jsonStr);
        Debug.Log (myObject3.level);
        Debug.Log (myObject3.timeElapsed);
        Debug.Log (myObject3.playerName);
    }
    
    [System.Serializable]
    public class MyClass
    {
        public int level;
        public float timeElapsed;
        public string playerName;
    }
}