I'm trying to convert some Java code that uses Jackson's @JsonSubTypes annotation to manage polymorphism.
Here is the working Java code:
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Comment.class, name = "CommentNote"), @JsonSubTypes.Type(value = Photo.class, name = "PhotoNote"), @JsonSubTypes.Type(value = Document.class, name = "DocumentNote") }) public abstract class Note implements Identifiable { [...]
Here is the Kotlin code I think would be equivalent:
JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") JsonSubTypes( JsonSubTypes.Type(value = javaClass<Comment>(), name = "CommentNote"), JsonSubTypes.Type(value = javaClass<Photo>(), name = "PhotoNote"), JsonSubTypes.Type(value = javaClass<Document>(), name = "DocumentNote") ) abstract class Note : Identifiable { [...]
But I get the following errors on each of the three "JsonSubTypes.Type" lines :
Kotlin: An annotation parameter must be a compile-time constant Kotlin: Annotation class cannot be instantiated
Any idea?
@JsonSubTypes – indicates sub-types of the annotated type. @JsonTypeName – defines a logical type name to use for annotated class.
@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
@JsonTypeInfo is used to indicate details of type information which is to be included in serialization and de-serialization.
I believe this has been resolved and nowadays you can write it like this:
import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes( JsonSubTypes.Type(value = Comment::class, name = "CommentNote"), JsonSubTypes.Type(value = Photo::class, name = "PhotoNote"), JsonSubTypes.Type(value = Document::class, name = "DocumentNote")) interface Note
Note the missing @ and class notation in the JsonSubTypes.Type
.
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