Search code examples
jacksonkotlin

How to use Jackson JsonSubTypes annotation in Kotlin


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?


Solution

  • Turns out it's a bug in the compiler, thanks for reporting it. To work around this issue, you can import JsonSubTypes.Type and use it without qualification:

    import org.codehaus.jackson.annotate.JsonSubTypes.Type
    
    JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type")
    JsonSubTypes(
        Type(value = javaClass<Comment>(), name = "CommentNote"),
        Type(value = javaClass<Photo>(), name = "PhotoNote"),
        Type(value = javaClass<Document>(), name = "DocumentNote")
    )
    abstract class Note : Identifiable {
        [...]