コード値を持つEnum型のJSONシリアライズ
Enum型のJSONシリアライズ
Enum型はJSONに変換すると、nameで変換される。コード値などを持った Enumの場合、コード値を使って変換したい場合があるので、一番簡単そうな方法を書いてみた。
SerializedName を使用
@SerializedName で、Jsonシリアライズ時の値を指定する。
import lombok.AllArgsConstructor; import lombok.Getter; import com.google.gson.annotations.SerializedName; @AllArgsConstructor public enum State { @SerializedName("CODE000") NORMAL("CODE000"), @SerializedName("CODE001") ERROR("CODE001"), @SerializedName("CODE002") INFO("CODE002"); @Getter private final String code; }
テスト
import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration public class StateTest { @Autowired private Gson gson; @Test public void toJson() { System.out.println(this.gson.toJson(State.ERROR)); } @SuppressWarnings("serial") @Test public void fromJson() { List<State> states = new ArrayList<State>(); states.add(State.ERROR); states.add(State.INFO); states.add(State.NORMAL); String json = this.gson.toJson(states); System.out.println(json); Type listType = new TypeToken<List<State>>() {}.getType(); List<State> actuals = new Gson().fromJson(json, listType); actuals.forEach(actual -> { System.out.println(actual); }); } }
@Test toJson の出力結果
"CODE001"
@Test fromJson の出力結果
["CODE001","CODE002","CODE000"] ERROR INFO NORMAL