2

I have a simple spring rest controller that looks like this.

@RestController
public class MyController {

@RequestMapping(path = "mapping", method = RequestMethod.POST, produces = {"application/json"})
    public MyResponse create(@RequestBody MyModel requestParam
    ) throws InvalidApplicationSentException, AuthenticationFailedException {
 // method body
}

Here is the MyModel class that's used as a request parameter.

public class MyModel {
    private RequestType requestType;
    // a lot of other properties ..
}

Now when i try to call this endpoint passing an invalid value for RequestType I get back an exeption:

org.springframework.http.converter.HttpMessageNotReadableException
Could not read document: Can not construct instance of com.mypackage.RequestType from String value 'UNDEFINED': value not one of declared Enum instance names: [IMPROTANT, NOT_IMPORTANT]

Is there a way that spring would set the enum to null when passed incorrect value and not throw an error?

I'm using spring 4 and I would prefer configuration with annotations and not xml files

1 Answer 1

3

You need to implement a custom JSON serialization method in your enum class http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson

Use @JsonCreator in your enum and on null or undefined value just return null to get going.

@JsonCreator
public static RequestType create(String value) {
    if(value == null) {
        return null;
    }
    for(RequestType v : values()) {
        if(value.equals(v.getName())) {
            return v;
        }
    }
    return null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.