LoginSignup
0
0

More than 1 year has passed since last update.

【Unity】JsonUtilityの[Serializable]について

Last updated at Posted at 2021-09-26

はじめに

  • リストをJSONで送信するにはクラスを囲うラッパーが必要.
  • しかし,サーバー側ではJsonUtilityがうまく働かずに空のJson{}が返ってきていた問題を解決.

開発環境

  • Unity 2019.4.23f

動いたコード

クラス定義の部分

class.cs
// ↓これがないと空の要素になる
[System.Serializable]
public class Tverts{
    public float x;
    public float y;
    public float z;
    public Tverts(float a,float b,float c){
        x=a;
        y=b;
        z=c;
    }
}
// ↓これがないと空の要素になる
[System.Serializable]
public class Tfaces{
    public int f1;
    public int f2;
    public int f3;
    public Tfaces(int a,int b,int c){
        f1=a;
        f2=b;
        f3=c;
    }
}
// ラッパークラス
public class Wrapper
{
    public List<Tverts> tverts;
    public List<Tfaces> tfaces;
}

クラスの使用部分

_.cs
        Wrapper test = new Wrapper(); 
        test.tverts = new List<Tverts>();
        test.tfaces = new List<Tfaces>();
        test.tfaces.Add(new Tfaces(1,1,1));
        test.tverts.Add(new Tverts(1.0f,1.0f,1.0f));
        string testjson = JsonUtility.ToJson(test);
_.JSON
{"tverts":[{"x":1.0,"y":1.0,"z":1.0,"weight":0.0}],"tfaces":[{"f1":1,"f2":1,"f3":1}]}

つまりどういうこと?

ラッパーされる側のクラスには[Serializable]が無いとJSON化できない(空のJsonが返ってくる).ただしJsonUtility.ToJson()に渡すクラス(Object)は[Serializable]されている必要がない(Publicで宣言されていればOK).

*ただしUnty公式ではJson化する全てのオブジェクトを[Serializable]するよう勧めているので,おとなしくすべて[Serializable]しましょう.

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