user3159152
user3159152

Reputation: 611

Jackson custom serialization getter

Let's say I have a POJO like:

public class User {
     private Long id;
     private String username;

     // usual getters and setters
     ....

     // only for serialisation purposes
     public String getUpperUsername() {
         return this.id % 2 == 0 ? username : username.toUpperCase();
     }


}

I would like to make a conditional serializer so that it serialises a different value that the actual one if some conditions are satisfied.

I looked at @JsonGetter but apparently it's deprecated, @JsonProperty doesn't seem to work.

Do you have any idea?

Thank you in advance :)

Upvotes: 7

Views: 12061

Answers (2)

makasprzak
makasprzak

Reputation: 5220

@JsonProperty works actually for me when I use it like this:

public class User {
      private Long id;
      private String username;

      public Long getId() {
         return id;
      }

      public void setId(Long id) {
         this.id = id;
      }

      public String getUsername() {
         return username;
      }

      public void setUsername(String username) {
         this.username = username;
      }

      @JsonProperty("username")
      public String getUppercaseUsername() {
         return this.id % 2 == 0 ? username : username.toUpperCase();
      }
}

See a test example here.

You can also go for a custom serializer, like here if you want to separate this uppercasing logic from the entity itself.

The truth however is that this a business logic, which should not be handled by a serializer - this is a design failure. Instead map the username elsewhere and use Jackson only for serialization - it's the purpose of this library.

Upvotes: 12

Kysil Ivan
Kysil Ivan

Reputation: 1047

You could try to write custom serializer implementing JsonSerializer and using @JsonSerialize then: http://www.baeldung.com/jackson-custom-serialization
But it seems like overkill.

Also, if it is acceptable, you could try to put logic of getUpperUsername() in usual getter.

PS: Strange that @JsonProperty does not work, it match here.

Upvotes: 2

Related Questions