java - Jackson:如何动态设置属性的别名
问题描述
我知道 Jackson 支持 Mixin,我可以为以下属性设置别名:
public final class Rectangle {
private int w;
public Rectangle(int w) {
this.w = w;
}
public int getW() { return w; }
}
}
abstract class MixIn {
MixIn(@JsonProperty("width") int w) { }
@JsonProperty("width") abstract int getW();
}
并这样做:
objectMapper.addMixInAnnotations(Rectangle.class, MixIn.class);
但我不想用注释来做。我想动态添加别名,例如:
objectMapper.addAlias(Rectangle.class, "w", "width")
有没有办法做到这一点?
注意:也可以接受 动态排除属性等解决方案
解决方案
您可以使用 custom 来实现这一点,AnnotationIntrospector
您可以在其中拦截和修改 Jackson 检测和使用@JsonProperty
(即使字段/方法未注释)
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
public class DynamicPropertyAliasIntrospector extends JacksonAnnotationIntrospector
{
@Override
public PropertyName findNameForSerialization(Annotated a)
{
// if get method has @JsonProperty, return that
PropertyName pn = super.findNameForSerialization(a);
if (a.hasAnnotation(JsonProperty.class)) {
return pn;
}
// if not annotated, value may be set dynamically
if (a.getName().equals("getW")) {
// value may be set from external source as well (properties file, etc)
pn = new PropertyName("width");
}
return pn;
}
}
用法:将自定义注释内省器的实例传递给对象映射器:
public static void main(String[] args)
{
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new DynamicPropertyAliasIntrospector());
Rectangle r = new Rectangle(3);
try {
mapper.writeValue(System.out, r);
} catch (IOException e) {
e.printStackTrace();
}
}
输出:
{"width":3}
推荐阅读
- java - 过滤 ACTION_PROCESS_TEXT 以在检测到电话号码时执行操作
- node.js - 无法将图像文件发布到服务器
- postgresql - 使用新添加的列更新表,该列包含来自同一表旧列的数据,但已修改(展平)jsonb
- postgresql - 为什么这个嵌套的 INNER JOIN 在 POSTGRESQL 中不起作用?
- azure - 通过 template.json 文件从 Storageacct 安装应用程序...我们需要通过参数传递 storageName 和 Key,因此它不是硬编码的
- c# - 在 TFS 中创建单独的搁置集
- tcl - 传递 $args 作为 vsim 参数的替代会产生错误
- javascript - 使用方法包括()检查字符串是否出现在数组中表示的字符返回真 - 从字符串中删除字符
- r - 带有 distHaversine 的 distm() 是否给出不准确的结果?
- reactjs - 类型“JSX.Element”不可分配给类型“元素”