SerializationFeature.WRAP_ROOT_VALUE作为杰克逊JSON中的注释 [英] SerializationFeature.WRAP_ROOT_VALUE as annotation in jackson json
本文介绍了SerializationFeature.WRAP_ROOT_VALUE作为杰克逊JSON中的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以将SerializationFeature.WRAP_ROOT_VALUE
的配置用作根元素上的注释,而不是使用ObjectMapper
?
Is there a way to have the configuration of SerializationFeature.WRAP_ROOT_VALUE
as an annotation on the root element instead using ObjectMapper
?
例如我有:
@JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
}
使用ObjectMapper:
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"));
}
结果:
{
"user":{
"id":1,
"name":"John"
}
}
是否有一种方法可以将此SerializationFeature
作为注释而不是objectMapper
上的配置?
Is there a way to have this SerializationFeature
as an annotation and not as an configuration on the 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
一起使之成为可能.
@JsonTypeName
and @JsonTypeInfo
together make it possible.
结果:
{
"user" : {
"id" : 1,
"name" : "John"
}
}
这篇关于SerializationFeature.WRAP_ROOT_VALUE作为杰克逊JSON中的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文