动态添加fasterxml Annotation? [英] Dynamic addition of fasterxml Annotation?
本文介绍了动态添加fasterxml Annotation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法动态设置@JsonProperty 注释,例如:
Is there a way to set @JsonProperty annotation dynamically like:
class A {
@JsonProperty("newB") //adding this dynamically
private String b;
}
或者我可以简单地重命名实例的字段吗?如果是这样,请给我一个想法.另外,ObjectMapper
可以以什么方式与序列化一起使用?
or can I simply rename field of an instance? If so, suggest me an idea.
Also, in what way an ObjectMapper
can be used with serialization?
推荐答案
假设您的 POJO
类如下所示:
Assume that your POJO
class looks like this:
class PojoA {
private String b;
// getters, setters
}
现在,您必须创建 MixIn 接口:
Now, you have to create MixIn interface:
interface PojoAMixIn {
@JsonProperty("newB")
String getB();
}
简单用法:
PojoA pojoA = new PojoA();
pojoA.setB("B value");
System.out.println("Without MixIn:");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pojoA));
System.out.println("With MixIn:");
ObjectMapper mapperWithMixIn = new ObjectMapper();
mapperWithMixIn.addMixInAnnotations(PojoA.class, PojoAMixIn.class);
System.out.println(mapperWithMixIn.writerWithDefaultPrettyPrinter().writeValueAsString(pojoA));
以上程序打印:
Without MixIn:
{
"b" : "B value"
}
With MixIn:
{
"newB" : "B value"
}
这篇关于动态添加fasterxml Annotation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文