问题
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