1

Suppose there is a class with a boolean property, its name starts with is:

    class Preferrable {
        var isPreferred: Boolean = true
    }

It is serialized to {"preferred":true}, dropping is part.

As mentioned in this question, to prevent it, we need to specify property name explicitly, using @JsonProperty("isPreferred") annotation.

That approach works perfectly with Java. But in case of Kotlin class with annotated property serialized form contains property duplication: {"preferred":true,"isPreferred":true}.

The workaround is to apply annotation to property getter. It doesn't work for data classes and as for me, this code looks a bit too much for just keeping property name as is:

class Preferrable {
    var isPreferred: Boolean = true
        @JsonProperty(value = "isPreferred")
        get() = field
}

What is the reason behind such behavior? Is it just a bug? Is there a simpler way to prevent is prefix dropping for Kotlin?

Adamovskiy
  • 1,376
  • 1
  • 12
  • 42

1 Answers1

3

Booleans are handled a bit differently from other data types. You need to explicitly use @get in the annotation:

@get:JsonProperty("isPreferred")
var isPreferred: Boolean = true

Note that this does work with data classes, e.g.

data class Preferrable(
    @get:JsonProperty("isPreferred")
    var isPreferred: Boolean = true
)

See this question for a bit more info (and a link to where this is discussed in more detail).

Yoni Gibbs
  • 6,518
  • 2
  • 24
  • 37