Is there a way to set @JsonProperty annotation dynamically like:
class A {
@JsonProperty("newB") //adding this dynamically
private String b;
}
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?
Assume that your POJO
class looks like this:
class PojoA {
private String b;
// getters, setters
}
Now, you have to create MixIn interface:
interface PojoAMixIn {
@JsonProperty("newB")
String getB();
}
Simple usage:
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With