有没有办法将 SerializationFeature.WRAP_ROOT_VALUE
配置为根元素上的注释,而不是使用 ObjectMapper
?
例如我有:
@JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
}
使用 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"));
}
结果:
{
"user":{
"id":1,
"name":"John"
}
}
有没有办法将此 SerializationFeature
作为注释而不是 objectMapper
上的配置?
使用依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
最佳答案
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
和 @JsonTypeInfo
共同使之成为可能。
结果:
{
"user" : {
"id" : 1,
"name" : "John"
}
}
关于java - SerializationFeature.WRAP_ROOT_VALUE 作为 jackson json 中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882478/