I am using Java Spring Boot @RestController with an object containing enum fields.
Spring automagically deserializes the JSON to the MyRequest
object.
@RestController
public class MyController {
@PostMapping(path = "/operation")
public ResponseEntity<MyResponse> operation(@Valid @RequestBody MyRequest request) {
...
}
}
public class MyRequest {
private MyEnum1 field1;
private MyEnum2 field2;
private MyEnum3 field3;
private MyEnum4 field4;
private MyEnum5 field5;
private MyEnum6 field6;
... // really a lot of various enum fields!
}
public enum MyEnum1 {
VAL1, VAL2, VAL3;
}
The problem is that if the JSON contains completely invalid value of the enum
field, the deserializer silently converts them to null
, without any exception.
{
"field1": "BLAHBLAH",
...
}
This is user-unfriendly and treacherous.
I know that I may write custom JSON deserializers for each enum, but the solution is cumbersome and non-elegant.
Is there a way to globally set the JSON enum deserializer to a "strict mode", so if the value is invalid it throws an exception? If so, how and where?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…