Issue
Please note: I am using Spring Boot here, not Spring MVC.
Java 8 and Spring Boot/Jackson here. I have the following enum:
public enum OrderType {
PARTIAL("partialOrder"),
FULL("fullOrder");
private String label;
OrderType(String label) { this.label = label; }
}
I would like to expose a POST
endpoint where the client can place the OrderType#label
as a request parameter, and Spring will know to convert the provided label into an OrderType
like so:
@PostMapping("/v1/myapp/orders")
public ResponseEntity<?> acceptOrder(@RequestParam(value = "orderType") OrderType orderType) {
// ...
}
And hence the client could make a call such as POST /v1/myapp/orders?orderType=fullOrder
and on the server, the controller would receive an OrderType
instance.
How can I accomplish this?
Solution
This was so easy, a cave man could even do it.
Enum:
public class MyEnum {
FIZZ("sumpin"),
BUZZ("sumpinElse");
@JsonValue
private String label;
MyEnum(String label) { this.label = label; }
public String getLabel() { return this.label; }
public static Optional<MyEnum> toMyEnum(String label) {
if (label == null) {
return Optional.empty();
}
for (MyEnum mine : MyEnum.values()) {
if (label.equals(mine.getLabel()) {
return Optional.of(mine);
}
}
throw new IllegalArgumentException("no supported");
}
}
Spring converter:
public class MyEnumConverter implements Converter<String,MyEnum> {
@Override
public MyEnum convert(String label) {
Optional<MyEnum> maybeMine = MyEnum.toMyEnum(label);
if (maybeMine.isPresent()) {
return maybeMine.get():
}
// else, you figure out what you want your app to do,
// thats not my job!
}
}
Register it:
@Configuration
public class YourAppConfig {
@Autowired
public void configureConverter(FormatterRegistry registry) {
registry.addConverter(new MyEnumConverter());
}
}
Support it from inside in a controller/resource:
@Post("/v1/foobar/doSomething")
public ResponseEntity<?> doSomething(@RequestParam(value = "mine") MyEnum mine) {
// ... whatever
}
Use the darn thing in an API call:
POST http://yourlousyapp.example.com/v1/foobar/doSomething?mine=sumpin
Answered By - hotmeatballsoup