LoginSignup
0
0

More than 5 years have passed since last update.

UnityのJsonUtilityを使った逆シリアル化のサンプル

Posted at

UnityのJsonUtillyを使った、配列を含む場合のJSONデータからオブジェクトへの逆シリアル化(デシリアライズ)のサンプル
(気軽に書いた🤠)

環境

Unity 2018.2.0f2

サンプル

sample.json
{
 "point": 30,
 "arr": [{"id": 1, "size": 10},{"id": 2, "size": 20}]
}
Sample.cs

void Start()
{
    const string str = "{\"point\": 30, \"arr\":[{\"id\": 1, \"size\": 10},{\"id\": 2, \"size\": 20}]}";
    var obj = JsonUtility.FromJson<Elephant>(str);
    print(obj.point); // 30
    print(obj.arr[0].id); // 1 
    print(obj.arr[1].size); // 20 
}
[Serializable]
class Elephant //†2
{
    public int point; //†1 
    public List<Monky> arr; //†1, †3
}

[Serializable]
class Monky //†2
{
    public int id;//†1
    public int size;//†1
}

†1: メンバー変数の名前を対象のJSONの変数名と同じにする必要がある
†2: クラス名は任意でよい
†3: Listではなく配列も可能

注意

JSON データからオブジェクトへの逆シリアル化するときは、JSONが配列の形ではだめらしい
[{},{},..]のような形になっていたものは、無理やり{"body":[{},{},..]}のような形に変換して対応することにした

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0