Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson custom serialization getter

Tags:

java

json

jackson

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 :)

like image 245
user3159152 Avatar asked Apr 09 '15 13:04

user3159152


People also ask

Does Jackson serialize getters?

Jackson doesn't (by default) care about fields. It will simply serialize everything provided by getters and deserialize everything with a matching setter.

Does Jackson use fields or getters?

Jackson uses the setter and getter methods to auto-detect the private field and updates the field during deserialization. Assume you have defined all the fields or properties in your Java class so that both input JSON and output Java class have identical fields.

Does Jackson need getters and setters?

Let's start with Jackson's default behavior during deserialization. Jackson can't deserialize into private fields with its default settings. Because it needs getter or setter methods.


2 Answers

@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.

like image 179
macias Avatar answered Oct 05 '22 02:10

macias


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.

like image 45
Kysil Ivan Avatar answered Oct 05 '22 04:10

Kysil Ivan