![](/img/trans.png)
[英]How to disable/enable jackson SerializationFeature.WRAP_ROOT_VALUE?
[英]SerializationFeature.WRAP_ROOT_VALUE as annotation in jackson json
有沒有辦法將SerializationFeature.WRAP_ROOT_VALUE
的配置作為根元素上的注釋而不是使用ObjectMapper
?
例如我有:
@JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
}
使用對象映射器:
@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"
}
}
我認為這已被要求為:
https://github.com/FasterXML/jackson-databind/issues/1022
因此,如果有人想要挑戰並有機會讓許多用戶感到高興(這肯定會很好),那么就可以爭奪了:)
除了值得注意的一件小事之外,您可以使用ObjectWriter
來啟用/禁用SerializationFeature
s。
String json = objectMapper.writer()
.with(SerializationFeature.WRAP_ROOT_VALUE)
.writeValueAsString(value);
如果您有時需要使用它,有時則不需要(在初始構建和配置后不應更改ObjectMapper
設置)。
您可以通過以下方式使用它,因此該屬性將應用於整個 objectMapper 使用。
static {
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.