Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...