jeudi 7 juillet 2016

SerializationFeature.WRAP_ROOT_VALUE as annotation in jackson json

Is there a way to have the configuration of SerializationFeature.WRAP_ROOT_VALUE as an annotation on the root element instead 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 an configuration on the objectMapper?

Using dependency:

<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.7.2</version>
</dependency>

Aucun commentaire:

Enregistrer un commentaire