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
) {
// ...
}
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.
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