java icon indicating copy to clipboard operation
java copied to clipboard

Kotlin support

Open emrul opened this issue 8 years ago • 5 comments

Hi, I'm wondering if there's any plan to support Kotlin code (similarly to how https://github.com/FasterXML/jackson-module-kotlin/blob/master/src/main/kotlin/com/fasterxml/jackson/module/kotlin/KotlinModule.kt does it)

Specifically: if I have a data class:

data class User(@JsonProperty("userName") val name: String)

Then the annotation is ignored (I believe because of how the Kotlin compiler generates related bytecode) and serializing an instance of this class will result in a JSON object with the key 'name' instead of 'userName'.

However, the following code behaves as expected:

class User(name: String) {
    @JsonProperty("userName")
    val name: String = name
}

emrul avatar May 20 '17 00:05 emrul

I am not familiar with kotlin

Contribution is welcomed.

taowen avatar May 20 '17 02:05 taowen

Hi @taowen thanks for the speedy response.

Today is the first time I've played with annotation processing in Kotlin or Java and the first time I've had to use JSONIter's extension functionality so I can't make a contribution....

However, I have made a Gist of code that works for the specific use case in this issue and posted it here: https://gist.github.com/emrul/2d446eff2084313fcb332f07e62b2ae8

I am able to use this, I hope it may help someone else in future.

Thanks again for this wonderful library.

emrul avatar May 20 '17 12:05 emrul

Your implementation looks fine. Since it contains reference to kotlin, it makes sense to keep it as an extension. You may open a pull request, like https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/annotation/JacksonAnnotationSupport.java

taowen avatar May 22 '17 16:05 taowen

I checked on the implementation and worked fine for me as well. Thanks for the post here.

hnrindani avatar Jan 02 '18 10:01 hnrindani

Just a small note: You can get the JsonProperty, JsonIgnore and any other annotations to be applied to the fields simply by changing the annotation from i.e @JsonProperty to @field:JsonProperty.

Missing this out is pretty much the same as applying the annotation to the variables in the constructor, instead of the fields themselves. See this link from the official Kotlin Language Website for more info.

Besides that, for my own personal usage Jsoniter (0.9.23) supports Kotlin perfectly except for Boolean values (which is probably an issue I haven't looked at yet).

Note: I am using Dynamic Code Generation here, not Static or Reflection.

Update: Boolean values work except when the variable name starts with is. Got no clue why this happens.

luaugg avatar Jul 21 '18 16:07 luaugg