json-iterator / java

jsoniter (json-iterator) is fast and flexible JSON parser available in Java and Go
http://jsoniter.com/
MIT License
1.51k stars 520 forks source link

Kotlin support #55

Open emrul opened 7 years ago

emrul commented 7 years ago

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
}
taowen commented 7 years ago

I am not familiar with kotlin

Contribution is welcomed.

emrul commented 7 years ago

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.

taowen commented 7 years ago

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

hnrindani commented 6 years ago

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

luaugg commented 6 years ago

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.