Dynamic addition of fasterxml Annotation?

前端 未结 2 772
闹比i
闹比i 2021-01-24 04:20

Is there a way to set @JsonProperty annotation dynamically like:

class A {

    @JsonProperty(\"newB\") //adding this dynamically
    private String b;

}
         


        
2条回答
  •  日久生厌
    2021-01-24 04:54

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

提交回复
热议问题