this is a very late answer but, if it helps you or others, you should be able to change annotations at runtime. Check this link:
https://www.baeldung.com/java-reflection-change-annotation-params
Modifying annotations might be a bit messy and I prefer other options.
Mixin's are a good static option but if you need to change properties at runtime you can use a custom serializer (or deserializer). Then register your serializer with the ObjectMapper of your choosing (writing formats like json / xml are now provided for free via Jackson). Here are some additional examples:
custom serializer:
https://www.baeldung.com/jackson-custom-serialization
custom deserializer:
https://www.baeldung.com/jackson-deserialization
i.e.:
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));
}
class A
could be mix-in class to use for one or more target classes, to make field "b" be serialized as "newB". – WestleyString
fromwriteValueAsString()
– Nonoccurrence