2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SpringでリクエストパラメータをEnumに変換する

Posted at

はじめに

Enumで扱うべき値を一旦Stringで取得して変換する作業が面倒だったので良い方法を探してました。

変換方法

Enumを用意して@JsonValue@JsonCreatorを使用して取得と生成処理を書く。

EnvironmentType.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import java.util.stream.Stream;

public enum EnvironmentType {
    PRODUCTION(1),
    STAGE(2),
    DEVELOP(3);

    private int value;

    EnvironmentType(int value) {
        this.value = value;
    }

    @JsonValue
    public int getValue() {
        return value;
    }

    @JsonCreator
    public static EnvironmentType create(Integer value) {
        if (value == null) {
            return null;
        }
        return Stream.of(values())
                .filter(v -> value.equals(v.getValue()))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException());
    }
}

リクエストで使用するBeanにEnum型を使用してプロパティを定義する。

Request.java
import EnvironmentType;

public class Request {
    private EnvironmentType type;

    public EnvironmentType getType() {
        return type;
    }

    public void setType(EnvironmentType type) {
        this.type = type;
    }
}

終わりに

Jacksonのアノテーションを使えば楽に書けました。

2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?