I was looking for a good method because it was troublesome to get the value to be handled by Enum once with String and convert it.
Prepare an Enum and write the acquisition and generation process using @JsonValue
and @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());
}
}
Define properties using Enum type for Bean used in request.
Request.java
import EnvironmentType;
public class Request {
private EnvironmentType type;
public EnvironmentType getType() {
return type;
}
public void setType(EnvironmentType type) {
this.type = type;
}
}
It was easy to write using Jackson annotations.
Recommended Posts