首页 > 解决方案 > Jersey Jackson JSON attribute change globally

问题描述

I have a scenario that if there is an XML attribute (defined as @XmlAttribute) in the POJO then it should named differently in the JSON output.

@XmlAttribute(name = "value")
//@JsonProperty("value-new")
protected String value;

Now I can use @JsonProperty to define the new name. But I have plenty of such attributes in each POJO and the name change required is "common" for all of them (say add -new) at the end. Is it possible to do this globally ?

标签: jsonjacksonjersey-2.0

解决方案


您可以实现自己的PropertyNamingStrategy.

class XmlAttributePropertyNamingStrategy extends PropertyNamingStrategy {

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        XmlAttribute annotation = field.getAnnotation(XmlAttribute.class);
        if (annotation != null) {
            return defaultName + "-new";
        }
        return super.nameForField(config, field, defaultName);
    }
}

您可以按如下方式使用它:

ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); // enable fields
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE); // disable getters
mapper.setPropertyNamingStrategy(new XmlAttributePropertyNamingStrategy());

System.out.println(mapper.writeValueAsString(new Pojo()));

因为XmlAttribute注释在字段级别可用,我们需要启用字段可见性并禁用 getter。对于以下POJO

class Pojo {

    @XmlAttribute
    private String attr = "Attr";
    private String value = "Value";
    // getters, setters
}

上面的示例打印:

{"attr-new":"Attr","value":"Value"}

推荐阅读