有没有一种动态设置@JsonProperty注释的方法,比如:
class A {
@JsonProperty("newB") //adding this dynamically
private String b;
}或者我可以简单地重命名实例的字段吗?如果是这样的话,给我一个建议。另外,ObjectMapper可以以什么方式与序列化一起使用?
发布于 2014-08-14 19:19:22
假设您的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"
}发布于 2019-06-19 03:23:22
这是一个非常晚的答案,但是,如果它对您或其他人有帮助,您应该能够在运行时更改注释。请查看此链接:
https://www.baeldung.com/java-reflection-change-annotation-params
修改注解可能有点麻烦,我更喜欢其他选项。
混合是一个很好的静态选项,但如果您需要在运行时更改属性,则可以使用自定义序列化程序(或反序列化程序)。然后用你选择的ObjectMapper注册你的序列化程序(像json / xml这样的编写格式现在是通过json免费提供的)。下面是一些额外的示例:
定制序列化程序:https://www.baeldung.com/jackson-custom-serialization
自定义反序列化器:https://www.baeldung.com/jackson-deserialization
即:
class A {
// @JsonProperty("newB") //adding this dynamically
String b;
}
class ASerializer extends StdSerializer<A> {
public ASerializer() {
this(null);
}
public ASerializer(Class<A> a) {
super(a);
}
@Override
public void serialize(A a, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (a == null) {
gen.writeNull();
} else {
gen.writeStartObject();
gen.writeStringField("newB", a.b);
gen.writeEndObject();
}
}
}
@Test
public void test() throws JsonProcessingException {
A a = new A();
a.b = "bbb";
String exp = "{\"newB\":\"bbb\"}";
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(A.class, new ASerializer());
mapper.registerModule(module);
assertEquals(exp, mapper.writeValueAsString(a));
}https://stackoverflow.com/questions/25290915
复制相似问题