@JsonRootName

The @JsonRootName annotation is used - if wrapping is enabled - to specify the name of the root wrapper to be used.

Wrapping means that instead of serializing a User to something like:

{
    "id":1,
    "name": "John"
}

It's going to be wrapped like this:

{
    "User":{
        "id": 1,
        "name": "John"
    }
}

So, let's look at an example -- we're going to use the @JsonRootName annotation to indicate the name of this potential wrapper entity:

@JsonRootName(value= "user")
public class UserWithRoot{
    public int id;
    public String name;
}

By default, the name of the wrapper would be the name of the class - UserWithRoot。By using the annotation, we get the cleaner- looking user

@Test
public void test06() throws Exception {
    UserWithRoot userWithRoot = new UserWithRoot(1, "jianglei");
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);

    String s = mapper.writeValueAsString(userWithRoot);
    System.out.println(s);

}
{
    "user":{
        "id": 1,
        "name": "John"
    }
}

results matching ""

    No results matching ""