Charles Bryant
Charles Bryant

Reputation: 1025

Java deserialise json to implementation of abstract object open closed principle

I have polymorphic types of Varchar, Integer and Float that extend a base class.

I have had to add the following to the base class so I can use it in a rest api.

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(name = "VarcharField", value = VarcharField.class),
        @JsonSubTypes.Type(name = "IntegerField", value = IntegerField.class),
        @JsonSubTypes.Type(name = "FloatField", value = FloatField.class)
})
public abstract class Field<T> implements FieldType<T>, Serializable {

My issue with this is that it breaks the open closed principle, is there anyway to get around this, an external config perhaps?

Upvotes: 0

Views: 50

Answers (1)

lexicore
lexicore

Reputation: 43681

If use JsonTypeInfo.Id.CLASS or JsonTypeInfo.Id.MINIMAL_CLASS, you will not need to specify subtypes.

Upvotes: 1

Related Questions