简体   繁体   中英

Spring MVC @RequestBody and partial object/json binding

I have a large object which can be updated in a few steps. I'am facing a partial binding problem. My service consumes json and I can not use @InitBinder along with @RequestBody. Cutting this object to a few small ones is not good a solution, because there is a lot of cross-field validations between steps.

Do you have any ideas how to solve this? I'am looking for a clean solution like: registering a specific object mapper for given @RequestMapping or something like that. Thanks for help.

You should be able to use a PATCH HTTP method

Its the preferred method that you would use when you need partial updates, like in your case when you want to update just a few fields of a resource

Spring MVC added a support for it in the version 3.2, so you can do something like

@RequestMapping(value="/patch", method=RequestMethod.PATCH, consumes=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String patch(@RequestBody Foo foo)    {
    return foo.toString();
}

and when sending the request, add only the properties you want to update to your PATCH request, the properties that are null or omited won't be updated

In the lack of better Spring MVC PATCH reference, I'm linking this SO thread as an interesting read Spring MVC PATCH method: partial updates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM