Enum annotations in Kotlin

2019-02-17 06:44发布

问题:

I have an enumeration that is serialized/deserialized by Gson:

enum class PacketType {
    NONE;
    [SerializedName("request")]
    REQUEST;
    [SerializedName("response")]
    RESPONSE;
    [SerializedName("event")]
    EVENT;
}

Unfortunately, I noticed that Gson ignores SerializedName annotations and uses upper case names for enum values. I decided to find out why serialization doesn't work as intended and found out that Kotlin drops all annotations for enum values. How can I make these annotations appear in generated bytecode?

回答1:

Looks like a bug to me. Please report to the issue tracker.

As a temporary workaround, you can write this class in Java



回答2:

The issue is now fixed, your code now works fine in Kotlin M9 (0.9.66). If you upgrade to that it'll work as you expect.

e.g.

app build.gradle

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 compile 'org.jetbrains.kotlin:kotlin-stdlib:0.9.66'
 compile 'com.google.code.gson:gson:2.3'
}

top-level build.gradle

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:0.13.2'
    classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:0.9.+'
 }
}

I confirmed this by making an enum with no relation between the enum names and SerializedName names, and it worked as expected.