https://kotlinlang.org logo
m

maxmello

08/18/2021, 2:21 PM
Hey 👋 I had a weird behavior just now and wanted to understand it:
Copy code
data class Example(@get:JsonProperty("element") val elements: List<Element> = listOf())
I remembered somehow that you need to add the get: part to a JsonProperty annotation such that it would be at the getter and not the field from Javas point of view, or else it woudn’t work right (which seems to be not the case after all), but this code above resulted in the following exception:
Copy code
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `int` from Array value (token `JsonToken.START_ARRAY`)
Now I strongly assume this is because List has a method
get
with parameter of type
Int
, but is this really how this annotation format should work? How would I even attach an annotation to the java getter in this case then? I fixed it now by removing the get:, just curious 🤔
d

dinomite

08/18/2021, 3:25 PM
get:
is an example of a use-site target; it restricts what the annotation applies to
In the context of Kotlin classes, declaring
val
or
var
parameters does many things: creates a constructor parameter, creates a backing field for that parameter, and creates getters & setters
Using
@get:JsonProperty
means that the
@JsonProperty
annotation will only be applied to the getter, not any of the other contexts
m

maxmello

08/26/2021, 9:45 AM
Yeah I assumed that would be the case, but in my example above, the annotation seems to be applied to the List::get method, not elements get(), which returns the List. Just seems like an edge case when the annotated property has a method get() in addition to the get method from the property itself.
32 Views