Spring @RequestBody and Enum value
I've found what I need. http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson.
It was 2 steps.
- Override the toString method of the Reos enum
@Override
public String toString() {
return text;
}
- Annotate with @JsonCreator the fromText method of the Reos enum.
@JsonCreator
public static Reos fromText(String text)
And that's all.
I hope this could help others facing the same problem.
Spring map Enum in @RequestBody
EDIT: updated see comments
Your request body is an object with one field named status
of type DeviceStatus
, so you can probably use your Device
class
So:
class Device {
// will be validated in the controller
private String status;
// getter, setter, etc
}
// with:
public enum DeviceStatus {
ACTIVE, INACTIVE, DELETED, ARCHIVED;
}
and @RequestBody Foo foo
in the controller method signature:
public ResponseEntity<Void> changeStatus(@PathVariable final List<Integer> ids, @NotNull @RequestBody final Device device) {
try {
deviceService.updateStatus(ids, DeviceStatus.valueOf(device.getStatus()));
} catch(IllegalArgumentException ex) {
// throw some custom exception. device.getStatus() was invalid
} catch(NullPointerException ex) {
// throw some custom exception. device.getStatus() was null
}
// ...
How to handle requestbody to set valid values from enum?
So I made something like this
I've created static enum list
private static final List<String> NAME = Arrays.asList(
Name.ALEX.toString(),
Name.PETER.toString(),
Name.DUNCAN.toString();
And simple check in controller before executing service method
if (!Name.contains(nameDTO.getName)
{
throw new Exception;
}
How to custom convert String to enum in @RequestBody?
You can try to use JsonProperty
on enum directly
enum IdType {
@JsonProperty("drivingLicence")
DRIVING_LICENCE,
@JsonProperty("idCard")
ID_CARD,
@JsonProperty("passport")
PASSPORT;
}
If you want to have multimapping the simple thing would be defining mapping and using JsonCreator
on enum level:
enum IdType {
DRIVING_LICENCE,
ID_CARD,
PASSPORT;
private static Map<String, IdType> mapping = new HashMap<>();
static {
mapping.put("drivingLicence", DRIVING_LICENCE);
mapping.put(DRIVING_LICENCE.name(), DRIVING_LICENCE);
// ...
}
@JsonCreator
public static IdType fromString(String value) {
return mapping.get(value);
}
}
See also:
- Deserializing an enum with Jackson
Spring Enum list empty in @RequestBody
@JsonCreator
public static StatusEnum forValue(String value) {
return namesMap.get(StringUtils.lowerCase(value));
}
Problem is the usage of #lowerCase in forValue
!
Your keys in your map aren't lower-cased. That's why namesMap.get
can't find anything.
Spring Boot - Json RequestBody, String/Enum with/without quotation marks
In the case where you are using @RequestBody String myString
the payload of the http request is put in there as-is. So whatever you send will be placed in there. The content-type doesn't matter as it will copy the payload of the request as is.
In the second case, an actual JSON string is required to be able to convert to an enum. A JSON based String needs to have quotation marks else it isn't a JSON String. Something other than a string cannot be converted to an enum.
To convert from the payload of the body to the requested object Spring uses an [HttpMessageConverter
]. It will select the correct HttpMessageConverter
based on the Content-Type
header. In your case, assuming the defaults, this will result in the MappingJackson2HttpMessageConverter
. Which will use the body to convert to the enum. Which will then fail as it isn't a valid JSON string (no quotation marks).
What is a String in JSON is explained here.
Enums as Request Parameters in Spring Boot Rest
Your body is declared as simple enum type, not object. So instead of posting JSON object with braces try to post only a value, which is for example:
"JANUARY"
Related Topics
Using Streams to Convert a List of Objects into a String Obtained from the Tostring Method
Javax.Xml.Bind.Unmarshalexception: Unexpected Element (Uri:"", Local:"Group")
Alternative to Switch Case in Java
Connection Java - Mysql:Public Key Retrieval Is Not Allowed
How to Find Index of First Vowel in a String
Reading a Resource File from Within Jar
Springboot Data - No Property Registration Found
Mockito - Nullpointerexception When Stubbing Method
Convert Yyyy-Mm-Dd Hh:Mm:Ss.Sss Zzz Format Strin to Date Object
Splitting Data Inside Quotes and Comma Using Regex
Transaction Marked as Rollback Only: How to Find the Cause
How to Pass the Same Object Across Multiple Classes Java
In Java, Can You Modify a List While Iterating Through It
How to Check If a Date Is After Today Java