gpt4 book ai didi

java - 使用 FasterXML Jackson 进行奇怪的 JSON 序列化

转载 作者:行者123 更新时间:2023-12-01 08:53:05 24 4
gpt4 key购买 nike

我不明白为什么我会得到给定类的序列化 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;
}

}

当使用 fastxml.jackson 序列化类实例时,我得到:

{
"ID": "e0d62504-4dfb-4c92-b70b-0d411e8ed102",
"lawyerOffice": [
{
...
}
]
}

所以数组的名称是lawyerOffice。我希望律师办公室s

这是我使用的实现:

    <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 配置(注入(inject)到 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); // <-----
...

关于java - 使用 FasterXML Jackson 进行奇怪的 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com