从对象生成JSON的奇怪行为

时间:2016-08-09 11:48:19

标签: java json jackson

这是我的代码的一部分:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OAType", propOrder = {
    "cDefCamelTDPDataList",
})
public class OAType {

    @XmlElement(name = "c-def-camel-TDP-data-list", required = true)
    protected cDefCamelTDPDataListType cDefCamelTDPDataList;
    ...

当我用:

创建json时
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tag); // Object tag

我明白了:

{
"cDefCamelTDPDataList" : { },
"cdefCamelTDPDataList" : { },
...

我不明白哪里出错,杰克逊为什么要创建2次cDefCamelTDPDataList字段?

1 个答案:

答案 0 :(得分:0)

您已启用杰克逊使用字段。但默认情况下还启用了getter / setter。我假设你有一个名为getCdefCamelTDPDataList()的吸气剂。

如果您只想处理字段,则必须先禁用getter / setter:

mapper.setVisibility(JsonMethod.ALL, Visibility.NONE); // disable getters/setters/is...
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);