Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 734
aepurniet Avatar asked May 02 '26 09:05

aepurniet


2 Answers

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;
  }
}
like image 135
husayt Avatar answered May 05 '26 00:05

husayt


You can annotate your class with

@JsonIgnoreProperties(ignoreUnknown = true)

to have the property ignored by Jackson during deserialization.

like image 31
Thilo-Alexander Ginkel Avatar answered May 04 '26 22:05

Thilo-Alexander Ginkel