Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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":[{},{},..]}のような形に変換して対応することにした

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away