json - Jersey Jackson JSON attribute change globally
问题描述
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 ?
解决方案
您可以实现自己的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"}
推荐阅读
- sql - SQL - 使用连接添加查询参数
- java - 我可以在 JPA 实体构造函数中使用 use 'System.IdentityHashCode()' 吗?
- spring-boot - Livereload 不会在 chrome 上为 spring 重新加载静态文件
- kubernetes - ClusterIP 是否能够负载平衡多个 pod 的流量?
- php - 内部服务器从 ajax 发送导致的错误
- amazon-web-services - Lamba 执行角色 - 调用 putObject 时拒绝访问
- vb.net - Clipboard.GetText() 函数不适用于组框内的文本框控件
- mysql - MySQL 在 Raspberry Pi 3 的清单条目中没有与 linux/arm/v7 匹配的清单
- python - 如何使用python从驱动器的文件夹中检索文件?
- java - java.util.Calendar getMaximum 最后一天返回错误