有没有办法像这样动态设置@JsonProperty批注:
class A {
@JsonProperty("newB") //adding this dynamically
private String b;
}
还是可以简单地重命名实例的字段?如果是这样,建议我一个主意。
另外,
ObjectMapper
可以以什么方式与序列化一起使用? 最佳答案
假设您的POJO
类如下所示:
class PojoA {
private String b;
// getters, setters
}
现在,您必须创建MixIn接口:
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"
}