Force usage a getter for a 3rdparty class, when jackson default is set to field-level access

197 views
Skip to first unread message

John Lindwall

unread,
Jul 7, 2021, 8:41:37 PM7/7/21
to jackson-user
We are serializing/deserializing JSON using jackson 2.11.0 and  using visibility settings to force the use of field-level access instead of via setter/getters:

        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);

However, certain 3rdparty classes have specific properties that we want generated by getter methods, and not the raw field value.  We cannot modify these classes directly.  I tried doing a mixin to make this happen but never figured it out.  I'd prefer not to write a custom serializer/deserializer for this use case if possible.

Here's a simplified example: If a create a Foo object (below) and serialize it, I'd like the output to be: {"bar": "XXbarXX"}

public class Foo {
   private String bar = "bar";

  public String getBar() {
    return "XX" + bar + "XX";
  }
}

John Lindwall

unread,
Jul 8, 2021, 12:12:12 AM7/8/21
to jackson-user
Of course after posting this I found my solution. It was to use a mix-in after all. Something like:

public abstract class FooMixIn extends Foo {
  @Override
  @JsonGetter("bar");
  public abstract String getBar()
Reply all
Reply to author
Forward
0 new messages