SerializationFeature.WRAP_ROOT_VALUE as annotation in jackson json

Is it possible to configure the configuration of SerializationFeature.WRAP_ROOT_VALUE as annotation on the root element using ObjectMapper ?

For example, I have:

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

Using ObjectMapper:

 @Test public void whenSerializingUsingJsonRootName_thenCorrect() throws JsonProcessingException { UserWithRoot user = new User(1, "John"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); String result = mapper.writeValueAsString(user); assertThat(result, containsString("John")); assertThat(result, containsString("user")); } 

Result:

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

Is there a way to have this SerializationFeature as an annotation, and not as a configuration on an ObjectMapper ?

Using Dependency:

 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.2</version> </dependency> 
+5
source share
1 answer
 import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Test2 { public static void main(String[] args) throws JsonProcessingException { UserWithRoot user = new UserWithRoot(1, "John"); ObjectMapper objectMapper = new ObjectMapper(); String userJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user); System.out.println(userJson); } @JsonTypeName(value = "user") @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) private static class UserWithRoot { public int id; public String name; } } 

@JsonTypeName and @JsonTypeInfo let you do this.

Result:

 { "user" : { "id" : 1, "name" : "John" } } 
+6
source

All Articles