泽西·杰克逊JSON属性全局更改 [英] Jersey Jackson JSON attribute change globally

查看:86
本文介绍了泽西·杰克逊JSON属性全局更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,如果POJO中有一个XML属性(定义为@XmlAttribute),那么它在JSON输出中应使用不同的名称.

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;

现在,我可以使用@JsonProperty来定义新名称.但是我在每个POJO中都有很多这样的属性,最后,所有这些属性的名称更改都是"common"(例如add -new).是否可以在全球范围内这样做?

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 ?

推荐答案

您可以实现自己的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()));

由于XmlAttribute注释在字段级别可用,因此我们需要启用字段可见性并禁用getter.对于以下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
}

上面的示例打印:

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

这篇关于泽西·杰克逊JSON属性全局更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆