Spring @RequestBody without using a pojo?

theprogrammer :

I am using Spring Boot and I have a method defined like this in my controller

@PostMapping("/update)
public void update(@RequestBody User user) {
    ...
}

However in my post request from client(frontend or postman for example), I have something like this:

{
    "firstName" : "John",
    "lastName" : "Doe",
    "id" : 1234,
    "metaInfoId" : "5457sdg26sg4636"
}

The thing is my User pojo has only firstName, id and lastName instance fields in it.However in my request I have to send metaInfoId as well for some other needs. So how can I retrieve or separate metaInfoIdand User model in my controller method above?

Do I have to create another model class called UserModelRequest and add all User fields along with metaInfoId field and then use @RequestBody? Is there a way to simply remove metaInfoId from the request and then take everything else and dump it into User pojo? You could do this easily in nodejs for example(just splice your object and take what you need).

So is there a way to do it in java spring without having to create another model class?

mad_fox :

You can annotate your POJO with @JsonIgnoreProperties(ignoreUnknown = true) so the fields that it does not contain are ignored. Ex

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private int id;
    private String firstName;
    private String lastName;

    ... getters & setters ...
}

Additionally, you should not include metadata in the body of your rest request. The correct place for this information would be in a headers. This would change your method signature to:

@PostMapping("/update)
public void update(@RequestBody User user, @RequestHeader(value="metaInfoId") String metaInfoId) {
    ...
}

If you must add the information in the request, then your would need to update the User pojo class to include this field (Or have it extend a class with the metaInfoId field)

Lastly, you really don't want to create a new type. You can change the signature to accept a map and retrieve the necessary info like:

@PostMapping("/update)
public void update(@RequestBody Map<String, Object> userMap) {
    String metaInfoId = userMap.get("metaInfoId");

    ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
    final User user = mapper.convertValue(userMap, User.class);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86791&siteId=1