您可以实现自己的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"}