Difference in serialization of data class fields


#1

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

Spring response and controller:

data class SampleResponse (
  @JsonProperty("changedFieldA")
  val fieldA: String = "valueA"
) {
  @JsonProperty("changedFieldB")
  val fieldB: String = "valueB"
}

class SampleController {
  @GetMapping
  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?


#2

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.