I am working on a SpringBoot REST service. The REST service works when the UI sends the right JSON values (formatted).
Sometimes the UI team will forget to upper case a property value and cause an exception. I want to make the REST service handle such cases.
JSON property is being POSTed as
"category":"patient"
It is supposed to be POSTed with uppercase.
"category":"PATIENT"
The Java object property category is a ENUM
public enum StaffCategory {
PATIENT, EQUIPMENT
}
The ui model object
@JsonProperty("category")
private StaffCategory category;
@JsonProperty("category")
public StaffCategory getCategory() {
return category;
}
@JsonProperty("category")
public void setCategory(StaffCategory category) {
this.category = category;
}
@JsonProperty("category")
private StaffCategory category;
This is the error I get
Can not deserialize value of type model.constants.StaffCategory
from String "patient": value not one of declared Enum instance names: [PATIENT, EQUIPMENT]
Although UI team should stick to backend API specs, still you can use ObjectMapper configuration to overcome this specific scenario:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);
return mapper;
}
You dont need to convert it to uppercase because it lowers readability and also avoids maintainability.You only need to change your Enum
definition as:
public enum StaffCategory {
PATIENT("patient"), EQUIPMENT("equipment");
private String value;
private StaffCategory(String value) { this.value = value; }
@JsonValue
public String getValue() { return this.value; }
}
This way it get easily deserialized with no breaking your code or facing any problems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.