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 :)
Jackson doesn't (by default) care about fields. It will simply serialize everything provided by getters and deserialize everything with a matching setter.
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.
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.
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With