Normally, I always wrap my JSON objects within a simple parent JSON, which contains only one element which is the JSON being wrapped. Refer this link for more information. Jackson API for Java provides an easy way to do this without creating unnecessary wrapper classes.

The below class will be used to demonstrate this:

import com.fasterxml.jackson.annotation.JsonTypeName;

@JsonTypeName("hello")
public class Hello {
  public String name = "anonymous";
}

If you use this class and deserialize it into a string using Jackson’s ObjectMapper class, you will get:

{
  "name": "anonymous"
}

To wrap this object inside a parent wrapper object, use the below Jackson annotation:

import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)

This will wrap the JSON inside a parent JSON object containing only one object which is the wrapped Hello object:

{
  "hello": {
    "name": "anonymous"
  }
}

Note that the name hello comes from the value specified in the first code snippet.
That’s it. No need to create an extra class just to wrap the object. Lean and clean.

Happy Coding! 🙂