Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jackson JsonSubTypes annotation in Kotlin

Tags:

kotlin

jackson

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?

like image 352
clemp6r Avatar asked Oct 28 '14 10:10

clemp6r


People also ask

What is JsonSubTypes?

@JsonSubTypes – indicates sub-types of the annotated type. @JsonTypeName – defines a logical type name to use for annotated class.

What is get JsonProperty?

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.

What is @JsonTypeInfo?

@JsonTypeInfo is used to indicate details of type information which is to be included in serialization and de-serialization.


1 Answers

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.

like image 129
Gijs Sijpesteijn Avatar answered Sep 21 '22 08:09

Gijs Sijpesteijn