Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin, jackson: cannot annotate @JsonCreator in primary constructor

Tags:

kotlin

jackson

I want to annotate with @JsonCreator using a primary constructor, something like this:

// error
@JsonCreator class User(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}

But the @JsonCreator annotation gives an error "This annotation is not applicable to target 'class'".

Using a secondary constructor works, but is it the only (or best) way?:

// works, but is there a better way?
class User @JsonCreator constructor(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}
like image 501
Ray Zhang Avatar asked Oct 19 '25 17:10

Ray Zhang


1 Answers

What you describe here:

class User @JsonCreator constructor(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}

is actually explicitly specifying the primary constructor. You can differentiate the primary from the secondary by looking at the class declaration:

class User constructor(/** **/) { // <-- primary

    constructor(/** ... **/) { // <-- secondary

    }

}

if the constructor is part of the class header it is a primary constructor, if it is part of the class declaration (it is after the {) it is a secondary one.

like image 145
Adam Arold Avatar answered Oct 21 '25 11:10

Adam Arold