0

I need to deserialize a JSON to a Java class with a Serializable field. In the following Java class the value field is an interface, the idea is that the view can send values of types: String, Double, Long and ArrayList. If I change the type of value field from Serializable to Object, it works as expected.

public class UpdateAttribute implements Serializable {
    //..
    // There is something like: @JsonImplType(Object.class)
    private Serializable value;
}

My question is, there is such a way to define a default class type to the value field? Something like: @JsonImplType(Object.class)?

João Pedro Schmitt
  • 1,046
  • 1
  • 11
  • 25

1 Answers1

0

The solution to this problem is use an annotation from jackson-databind module. A similiar question was asked here: Jackson - How to specify a single implementation for interface-referenced deserialization?.

public class UpdateAttribute implements Serializable {
    //..
    @JsonDeserialize(as = Object.class)
    private Serializable value;
}

However, there is a detail to be considered. The setValue method of UpdateAttribute can't be declared with a Serializable argument. Because Jackson don't know about the casting from Object to Serializable. Therefore, the final class should look like:

public class UpdateAttribute implements Serializable {

    @JsonDeserialize(as = Object.class)
    private Serializable value;

    public void setValue(Object value) {
        this.value = (Serializable) value;
    }
}
João Pedro Schmitt
  • 1,046
  • 1
  • 11
  • 25