Difference in serialization of data class fields


Found out that constructor fields are handled differently by Jackson ( and Gson ).

Spring response and controller:

data class SampleResponse (
  val fieldA: String = "valueA"
) {
  val fieldB: String = "valueB"

class SampleController {
  fun handle(): SampleResponse {
    return SampleResponse()

Which should return:

    "changedFieldA": "valueA",
    "changedFieldB": "valueB"

But returns:

    "fieldA": "valueA",
    "changedFieldB": "valueB"

It seems JsonProperty for constructor field was ignored, and another field name was changed. It turns out that constructor field was not ignored, but in class com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector getter name getFieldA was replaced with fieldA and annotation of field was ignored.

Is it intended behaviour? And field annotations are not applied to getters? Or this is a problem of Jackson (Gson) to handle such getters and annotations?


Yes, this is intended behavior. See http://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets for documentation. Use @get:JsonProperty to get the behavior you expect.