Java – spring MVC @ requestbody map optional

I have a rest controller for this method:

@RequestMapping(value = "",method = { RequestMethod.POST },produces = { MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<?> add(@Valid @RequestBody MyModel myModel,Errors errors) {

        ...
        return new ResponseEntity<SomeObject>(someObject,HttpStatus.OK);
    }

In mymodel, there is a field ismeetingorsale, which is an enumeration (meetingsaleflag):

public enum MeetingSaleFlag {
    MEETING("MEETING"),SALE("SALE");
    private final String name;       
    private MeetingSaleFlag(String s) { name = s; }
    public boolean equalsName(String otherName) {
       return (otherName == null) ? false : name.equals(otherName);
    }
    public String toString() { return this.name; }
}

And it can map JSON with field "ismeetingorsale": "meeting"

However, the value in JSON may be "ismeetingorsale": "or completely missing, so in this case, I want to map the field to null If I change the field to optional < meetingsaleflag >

I have

So the question is how to map optional enumerations from JSON?

Solution

Thank Sotirios delimanolis for his comments. I can solve this problem

1) Add

<dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jdk8</artifactId>
        </dependency>

As a dependency

2) Reconfigure the Jackson mapper Register:

@Bean
    @Primary
    public ObjectMapper jacksonObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new Jdk8Module());
        return mapper;
    }

Or do this to register the jdk8 module

/**
 * @return Jackson jdk8 module to be registered with every bean of type
 *         {@link ObjectMapper}
 */
@Bean
public Module jdk8JacksonModule() {
    return new Jdk8Module();
}

Doing so will only register the add - on and retain the built - in Jackson configuration provided by spring boot

3) Results

Now, when the attribute is missing from the sent JSON, it will map to null (this is not so good. I expect it to give me an optional one, and I will be able to use. Ispresent()) When it is an empty string ("ismeetingorsale": ""), Jackson will return an error:

Which one looks good to me

Useful links: Jackson jdk8 module, spring MVC configure Jackson

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>