LoginSignup
8
6

More than 5 years have passed since last update.

GsonでEnumを処理する

Posted at
  • 環境:JDK8, gson-2.5

Gsonでenumをいい感じに処理する を見て気になったので。

GsonEnum.java
package org.example.javalabo;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class GsonEnum {
    public static void main(String args[]) {
        Gson gson = new Gson();
        assertThat(gson.fromJson("0", Platform.class), is(Platform.Twitter));
        assertThat(gson.fromJson("1", Platform.class), is(Platform.TwitterDM));
        assertThat(gson.toJson(Platform.Twitter), is("\"0\""));
        assertThat(gson.toJson(Platform.TwitterDM), is("\"1\""));
    }

    public enum Platform {
        @SerializedName("0")
        Twitter,
        @SerializedName("1")
        TwitterDM;
    }

}

intStringで変換がちょっとずれるということに目を潰れば@SerializedNameで簡単。
JSON と Enum の対応が String で良いなら何も問題はないと思われます。

8
6
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
8
6