我有以下设置在序列化和反序列化JSON期间启用根元素包装。我正在使用带有Spring MVC Rest的Jackson库。 我正在使用的Jackson库版本是2.7.4。
但是下面的设置没有指定我的REST服务返回的JSON对象中的ROOT元素。我在这里遗漏了一些东西,检查了很多帖子,大多数都只提到了下面的配置。
pom.xml文件如下
<jackson.version>2.7.4</jackson.version>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
构建Jackson对象映射器对象
private static MappingJackson2HttpMessageConverter buildJSONMessageConverter() {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
builder.serializationInclusion(Include.NON_NULL);
builder.featuresToEnable(DeserializationFeature.UNWRAP_ROOT_VALUE);
builder.featuresToEnable(SerializationFeature.WRAP_ROOT_VALUE);
builder.indentOutput(true);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(builder.build());
return converter;
}
类域定义
@JsonRootName(value = "Brand")
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class Brand{
....
}
返回的JSON没有Brand作为根节点