![](/img/trans.png)
[英]How to use fasterxml Jackson JSON serialization in Spring 4
[英]Strange JSON serialization with FasterXML Jackson
我不明白为什么我得到给定类的序列化JSON,如下所示。
这是从WSDL生成的类,因此我无法更改它:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Lawyer")
public class Lawyer extends Person {
@XmlElementWrapper(required = true)
@XmlElement(name = "lawyerOffice", namespace = "http://xxx/addressbook/external/v01/types")
protected List<LawyerOffice> lawyerOffices;
public List<LawyerOffice> getLawyerOffices() {
if (lawyerOffices == null) {
lawyerOffices = new ArrayList<LawyerOffice>();
}
return lawyerOffices;
}
public void setLawyerOffices(List<LawyerOffice> lawyerOffices) {
this.lawyerOffices = lawyerOffices;
}
}
当一个类实例使用fasterxml.jackson序列化时,我得到:
{
"ID": "e0d62504-4dfb-4c92-b70b-0d411e8ed102",
"lawyerOffice": [
{
...
}
]
}
因此,数组的名称是律师办公室 。 我希望lawyerOffice 秒 。
这是我使用的实现:
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
这是我的ObjectMapper配置(注入CXF中):
@Provider
@Consumes({ MediaType.APPLICATION_JSON, "text/json" })
@Produces({ MediaType.APPLICATION_JSON, "text/json" })
public class JsonProvider extends JacksonJsonProvider {
public static ObjectMapper createMapper() {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector primary = new DPAJaxbAnnotationIntrospector(mapper.getTypeFactory());
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
AnnotationIntrospector pair = AnnotationIntrospector.pair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.disable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
mapper.disable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
return mapper;
}
public JsonProvider() {
super();
this.setMapper(createMapper());
}
}
如何获得“正确的”列表名称?
我找到了解决方案。 我在objectMapper配置中启用了USE_WRAPPER_NAME_AS_PROPERTY_NAME
功能选项:
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector primary = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
AnnotationIntrospector pair = AnnotationIntrospector.pair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
...
mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME); // <-----
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.