FasterXML / jackson-dataformats-binary

Uber-project for standard Jackson binary format backends: avro, cbor, ion, protobuf, smile
Apache License 2.0
310 stars 133 forks source link

Writing CBOR ignores @JSONProperty in Kotlin #227

Closed StefanLobbenmeier closed 3 years ago

StefanLobbenmeier commented 3 years ago

I have this class:

class CoseKey(
    @JsonProperty("1") val alg : Int = 2,
    @JsonProperty("3") val contentType : Int = -25,
    @JsonProperty("-1") val minus1 : Int = 1,
    @JsonProperty("-2") val xCoordinate : ByteArray,
    @JsonProperty("-3") val yCoordinate : ByteArray,
)

which should read and write this key:

{1: 2, 3: -25, -1: 1, -2: h'76E5A2FC3023999DB5A77D6E34BA29761D0AC49CD8DFE8735AB30101D12D238A', -3: h'BB6A9EF22FAC7F42EF4F4C27798C7A746981F498254E9A0F724044EF268941E8'}

When I read this class from CBOR it is working just fine. But when I write it it instead produces:

{"alg": 2, "contentType": -25, "minus1": 1, "xcoordinate": h'76E5A2FC3023999DB5A77D6E34BA29761D0AC49CD8DFE8735AB30101D12D238A', "ycoordinate": h'BB6A9EF22FAC7F42EF4F4C27798C7A746981F498254E9A0F724044EF268941E8'}

Is there a different annotation I should use? In the Past I used @JsonProperty just fine for reading and writing JSON and maps, so it is strange that it here only works for reading them

StefanLobbenmeier commented 3 years ago

Also now that I am further looking at it, why are xcoordinate and ycoordinate lowercase while contentType stayed in camelCase? (Does not matter to me though, as I want to explicitly set the name via annotation anyway)

StefanLobbenmeier commented 3 years ago

I found out the issue - Kotlin puts the annotations on the private fields which Jackson does not scan. For writing this works:

class CoseKey(
    @get:JsonProperty("1") val alg : Int = 2,
    @get:JsonProperty("3") val contentType : Int = -25,
    @get:JsonProperty("-1") val minus1 : Int = 1,
    @get:JsonProperty("-2") val xCoordinate : ByteArray,
    @get:JsonProperty("-3") val yCoordinate : ByteArray,
)
StefanLobbenmeier commented 3 years ago

And for supporting both reading and writing remove the get: again and instead use the jackson kotlin module: https://github.com/FasterXML/jackson-module-kotlin/