Reputation: 1269
I'm not sure if this is possible, but I'd like to have an overloaded setter on a Jackson deserializable object. So that depending on the object in that field it deserializes differently.
Example
public class Thing {
private MyObject1 object;
public MyObject1 getObject() {
return object;
public void setObject(MyObject1 object) {
this.object = object;
}
public void setObject(MyObject2 object) {
this.object = translate1To2(object);
}
}
If this is not possible, would someone offer me an alternative approach? My concern is that in the simple case where there is only one setter, Jackson doesn't have to choose which object to deserialize the JSON as, so not sure if it even can.
UPDATE: The above gives a com.fasterxml.jackson.databind.JsonMappingException: Conflicting setter definitions for property "object"
as is.
Upvotes: 0
Views: 1067
Reputation: 1269
Because you cannot actually overload setters like this in Jackson, my solution was as follows:
I made a deserializer to translate MyObject2
to MyObject1
and had one setter, so my class looked like this:
public class Thing {
@JsonDeserialize(using = MyObjectDeserializer.class)
private MyObject1 object;
public MyObject1 getObject() {
return object;
public void setObject(MyObject1 object) {
this.object = object;
}
}
Upvotes: 0
Reputation: 2183
The best way, I think is add a Custom Deserialization class
@JsonDeserialize(using = ThingDeserializer.class)
public class Thing {
...
}
Example of deserialization here https://www.baeldung.com/jackson-deserialization
Then, your bean will be ever clean, and you make your own JSON as you want to have
Upvotes: 1