Spring Boot: Map JSON body with root node in @RequestBody

Say you have the following JSON:

{
  "rootNode": {
    "firstValue":"",
    "secondValue":""
  }
}

The class to use for this could look something like this:

public class MyValues {
  private String firstValue;
  private String secondValue;
  ...
}

This class will however not map directly to the JSON above via @RequestBody, and this is because the JSON contains a root node (“rootNode”)

The solution here is to wrap the MyValues class into a “root class” like this:

public class MyValuesWrapper {
  MyValues rootNode;
  ...
}

After this you should be able to parse the request body automatically with @ResponseBody like this:

 @PostMapping(value = "/myValues")
  public int postValues(@RequestBody MyValuesWrapper wrappedRequest) {
  
  // Optional: Unwrap for easier access
  MyValues request = wrappedRequest.getMyValues();
  ...

Hope this helps somebody (or me in the future 🙂 )

Tested on Spring Boot v2.3.8 and Java 11

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.