@JsonRootName注解可以用来包装对象序列化与顶层元素。我们可以将名称作为参数传递给@JsonRootName 批注。我们可以使用SerializationFeature 枚举 的“ WRAP_ROOT_VALUE” 功能,该功能可以使根值包装在单个属性JSON对象中,其中键是根名称。
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"; }
输出结果
{"user":{"empId":125,"empName":"Raja Ramesh"}}