Search code examples
javajsonjacksonpojo

ignoring calculated fields in deserialization


i have a class:

class MyClass {
  @Getter
  @Setter
  int a;

  @Getter
  @Setter
  int b;

  public int getADivB() {
    return a / b;
  }
}

when serializing i need all three properties to be serialized. however if another java process is deserializing the message i would like jackson to ignore the calculated field. (not ignore it all together as with @JSONIgnore)

deserialization code is:

String json = ... //get json from message
JsonNode root = this.mapper.readTree(json);
MyClass abdiv = this.mapper.readValue(root, MyClass.class);

Solution

  • What you need is to annotate calculated property with @JsonProperty so it will look like this:

    class MyClass {
      @Getter
      @Setter
      int a;
    
      @Getter
      @Setter
      int b;
    
      @JsonProperty
      public int getADivB() {
        return a / b;
      }
    }