LoginSignup
0
0

【Unity】eventというオブジェクトを含むJsonをパースする

Last updated at Posted at 2023-12-02

UnityのJsonUtilityを使って以下のようなJsonをパースしようとして詰まった。

{
    "id": 1,
    "event": {
        "broadcaster_user_id": "1337",
        "broadcaster_user_name": "Cool_User",
        "broadcaster_user_login": "cool_user"
    }
} 

Jsonのeventキー部分をパースするには、以下のようなクラスを書く必要があります。

[System.Serializable]
public class Hoge
{
    public int id;
    public event event;
}

[System.Serializable]
public class event 
{
    public string broadcaster_user_id;
    public string broadcaster_user_name;
    public string broadcaster_user_login;
}

が、これだとエラーとなります。
eventはC#で使われているキーワードなので、識別子に使う事ができません。
ではどうするか。

結論

識別子の頭に@をつけることで解決できました。

[System.Serializable]
public class Hoge
{
    public int id;
    public @event @event;
}

[System.Serializable]
public class @event
{
    public string broadcaster_user_id;
    public string broadcaster_user_name;
    public string broadcaster_user_login;
}

これでeventが無事パースできました。
この頭に@がついた識別子は、逐語的識別子と呼ぶらしいです。

参考
https://atmarkit.itmedia.co.jp/fdotnet/dotnettips/250identifier/identifier.html

ちなみに、@を抜いた識別子も逐語的識別子として定義したものと同一とみなされるようです。
前述のような既にキーワードで使用されているケースでなければ、普通に使えます。

int @foo = 10;
foo += 15; // @fooとして定義した変数に代入される
Debug.Log(@foo); // 結果は25
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