动态添加fastxml注释吗? [英] Dynamic addition of fasterxml Annotation?

查看:86
本文介绍了动态添加fastxml注释吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法像这样动态设置@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));

以上程序打印:

Above program prints:

Without MixIn:
{
  "b" : "B value"
}
With MixIn:
{
  "newB" : "B value"
}

这篇关于动态添加fastxml注释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆