gpt4 book ai didi

java - 动态添加fasterxml注解?

转载 作者:行者123 更新时间:2023-11-30 03:47:26 26 4
gpt4 key购买 nike

有没有办法动态设置@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"
}

关于java - 动态添加fasterxml注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25290915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com