Reputation: 25802
I'd like to implement UPDATE (method PUT) operation for REST api. From front-end application my controller method expects map of values, for example:
@PutMapping(value = "/profile")
public UserDto updateProfile(JwtAuthenticationToken jwtAuthenticationToken, @RequestBody Map<String, ?> userForm) {
...
}
I'd like to use map as the request body and not POJO because with help opf map I can declare 3 states for each property:
with POJO I'm unable to handle #1 from the list above - the property is always present with null or not null value
In my service method I have to merge properties from the map with my User
object based on the 3 rules above.
For sure, I can do it in my custom code with reflection api but looking for some existing util which can help me with this task... some kind of
user = BeanUtils.merge(userForm, user);
Please advise if any exists.
Upvotes: 1
Views: 840
Reputation: 26926
You can convert your User
object to a Map
and work as follow:
User
to a Map
original objectuserForm
to original
User
classBasically the code is something like that:
private ObjectMapper objectMapper;
...
public User merge(User originalUser, Map newUserMap) {
Map originalUserMap = objectMapper.convertValue(originalUser, Map.class);
originalUserMap.putAll(newUserMap);
return objectMapper.convertValue(originalUserMap, User.class);
}
...
User userAfterModifications = merge(user, userForm);
... // Do what you need with the updated user
Note that you need to be sure that the Map implementation supports null values.
Upvotes: 2