How to read additional JSON attribute(s) which is not mapped to a @RequestBody model object in Spring boot

Randhir Ray :

I have a RestController which looks like this

@RequestMapping(value = "/post", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> test(@RequestBody User user) {

    System.out.println(user);
    return ResponseEntity.ok(user);
}     

And the User model which looks like this

class User {

    @NotBlank
    private String name;
    private String city;
    private String state;

}

I have a requirement wherein users can pass some extra additional attribute(s) in the input JSON, something like this

{
"name": "abc",
"city": "xyz",
"state": "pqr",
"zip":"765234",
"country": "india"
}

'zip' and 'country' are the additional attributes in the input JSON.

Is there any way in Spring Boot we can get these additional attributes in the Request Body ?

I know a way wherein I can use either a "Map" or "JsonNode" or "HttpEntity" as Requestbody parameter. But I don't want to use these classes as I would loose the javax.validation that can be used inside "User" model object.

M. Deinum :

Extend your User DTO with a Map<String, String> and create a setter which is annotated with @JsonAnySetter. For all unknown properties this method will be called.

class User {

    private final Map<String, Object> details= new HashMap<>);

    @NotBlank
    private String name;
    private String city;
    private String state;

    @JsonAnySetter
    public void addDetail(String key, Object value) {
      this.details.add(key, value);
    }

    public Map<String, Object> getDetails() { return this.details; }
}

Now you can obtain everything else through the getDetails().

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415729&siteId=1