Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic addition of fasterxml Annotation?

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?

like image 672
Jayanth Avatar asked Sep 13 '25 12:09

Jayanth


1 Answers

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"
}
like image 137
Michał Ziober Avatar answered Sep 15 '25 03:09

Michał Ziober