泽西·杰克逊JSON属性全局更改 [英] Jersey Jackson JSON attribute change globally
问题描述
我有一个场景,如果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屋!