The @JsonRootName annotation can be used to wrap an object to serialize with a top-level element. We can pass the name as a parameter to @JsonRootName annotation. We can use the "WRAP_ROOT_VALUE" feature of SerializationFeature enum that can be enabled to make root value wrapped within a single property JSON object where the key is a root name.
Example
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonRootNameAnnotationTest {
public static void main(String args[]) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(new Employee());
System.out.println(jsonString);
}
}
@JsonRootName(value = "user")
class Employee {
public int empId = 125;
public String empName = "Raja Ramesh";
}Output
{"user":{"empId":125,"empName":"Raja Ramesh"}}