Jersey Jackson JSON attribute change globally

六眼飞鱼酱① 提交于 2019-12-24 16:04:02

问题


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 ?


回答1:


You can implement your own 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);
    }
}

You can use it as below:

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()));

Because XmlAttribute annotation is available on field level we need to enable fields visibility and disable getters. For below POJO:

class Pojo {

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

Above example prints:

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


来源:https://stackoverflow.com/questions/54749919/jersey-jackson-json-attribute-change-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!