Skip to content

Instantly share code, notes, and snippets.

@trenthudy
Last active November 17, 2023 20:43
Show Gist options
  • Save trenthudy/24e96fe38640ee9fe02d332ac970d8e3 to your computer and use it in GitHub Desktop.
Save trenthudy/24e96fe38640ee9fe02d332ac970d8e3 to your computer and use it in GitHub Desktop.
Deserializing Kotlin enum classes with Gson
package io.hudepohl
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.google.gson.reflect.TypeToken
import org.junit.Assert.assertTrue
import org.junit.Test
private const val testJson =
"""
[
{
"fullName" : "Johnny",
"jobDesc" : "android dev"
},
{
"fullName" : "Joey",
"jobDesc" : "ios dev"
},
{
"fullName" : "Suzzie",
"jobDesc" : "ruby dev"
},
{
"fullName" : "Sally",
"jobDesc" : "SOMETHING THAT DOESN'T MAP TO OUR ENUM"
}
]
"""
enum class Occupation {
@SerializedName("android dev")
ANDROID_DEVELOPER,
@SerializedName("ios dev")
IOS_DEVELOPER,
@SerializedName("ruby dev")
RUBY_DEVELOPER,
UNKNOWN;
}
class KotlinEnumClassGsonDeserializationTest {
/**
* Option 1: Make the enum parameter nullable, with no default value.
*
* Result: When the value is not mapped to any of the enum values, the parameter is set to null.
*/
data class Person1(
@SerializedName("fullName") val name: String,
@SerializedName("jobDesc") val occupation: Occupation?
)
@Test
fun testParseNullableNoDefaultValue() {
val type = object : TypeToken<List<Person1>>() {}.type
val people: List<Person1> = Gson().fromJson(testJson, type)
assertTrue(people[0].occupation == Occupation.ANDROID_DEVELOPER)
assertTrue(people[1].occupation == Occupation.IOS_DEVELOPER)
assertTrue(people[2].occupation == Occupation.RUBY_DEVELOPER)
assertTrue(people[3].occupation == null)
}
/**
* Option 2: Make the enum parameter non-null, with no default value.
*
* Result: When the value is not mapped to any of the enum values, Gson will disobey Kotlin's
* null safety and set a non-null type to null!
*/
data class Person2(
@SerializedName("fullName") val name: String,
@SerializedName("jobDesc") val occupation: Occupation
)
@Test
fun testParseNonNullNoDefaultValue() {
val type = object : TypeToken<List<Person2>>() {}.type
val people: List<Person2> = Gson().fromJson(testJson, type)
assertTrue(people[0].occupation == Occupation.ANDROID_DEVELOPER)
assertTrue(people[1].occupation == Occupation.IOS_DEVELOPER)
assertTrue(people[2].occupation == Occupation.RUBY_DEVELOPER)
assertTrue(people[3].occupation == null)
}
/**
* Option 3: Make the enum parameter nullable, with a default value.
*
* Result: When the value is not mapped to any of the enum values, the parameter is set to null.
*/
data class Person3(
@SerializedName("fullName") val name: String,
@SerializedName("jobDesc") val occupation: Occupation? = Occupation.UNKNOWN
)
@Test
fun testParseNullableDefaultValue() {
val type = object : TypeToken<List<Person3>>() {}.type
val people: List<Person3> = Gson().fromJson(testJson, type)
assertTrue(people[0].occupation == Occupation.ANDROID_DEVELOPER)
assertTrue(people[1].occupation == Occupation.IOS_DEVELOPER)
assertTrue(people[2].occupation == Occupation.RUBY_DEVELOPER)
assertTrue(people[3].occupation == null)
}
/**
* Option 4: Make the enum parameter non-null, with a default value.
*
* Result: When the value is not mapped to any of the enum values, Gson will disobey Kotlin's
* null safety and set a non-null type to null!
*/
data class Person4(
@SerializedName("fullName") val name: String,
@SerializedName("jobDesc") val occupation: Occupation = Occupation.UNKNOWN
)
@Test
fun testParseNonNullDefaultValue() {
val type = object : TypeToken<List<Person4>>() {}.type
val people: List<Person4> = Gson().fromJson(testJson, type)
assertTrue(people[0].occupation == Occupation.ANDROID_DEVELOPER)
assertTrue(people[1].occupation == Occupation.IOS_DEVELOPER)
assertTrue(people[2].occupation == Occupation.RUBY_DEVELOPER)
assertTrue(people[3].occupation == null)
}
}
@trenthudy
Copy link
Author

trenthudy commented Mar 26, 2019

Based on these tests, any parameter that is typed as an enum class and deserialized with Gson is nullable (even if it's a non-null Kotlin parameter!). Scary...

To support an enum class that will change over time, we should set all enum class parameters to nullable and read their values with Kotlin when statements:

    enum class Occupation {

        @SerializedName("android dev")
        ANDROID_DEVELOPER,

        @SerializedName("ios dev")
        IOS_DEVELOPER,

        @SerializedName("ruby dev")
        RUBY_DEVELOPER,

        UNKNOWN;
    }

    data class Person(
        @SerializedName("fullName") val name: String,
        @SerializedName("jobDesc") val occupation: Occupation?
    )

    fun getOccupationText(person: Person): String {
        
        return when (person.occupation) {
            Occupation.ANDROID_DEVELOPER -> "Android Nerd"
            Occupation.IOS_DEVELOPER -> "iOS Nerd"
            Occupation.RUBY_DEVELOPER -> "Ruby Nerd"
            else -> "Unknown Nerd"
        }
    }

In this example, the else case will handle Occupation.UNKNOWN and null.

@trenthudy
Copy link
Author

Also found a Gson issue that relates to this: google/gson#608. It doesn't look like there are any plans to fix this behavior at the moment.

@safaorhan
Copy link

Thanks for the gist, good finding. I was experiencing the same and looking for an option to set a default value. Like:

enum class Occupation {

        @SerializedName("android dev")
        ANDROID_DEVELOPER,

        @SerializedName("ios dev")
        IOS_DEVELOPER,

        @SerializedName("ruby dev")
        RUBY_DEVELOPER,

        @DefaultValue
        UNKNOWN;
    }

But sadly, it's not implemented.

I think I'll take the path of making all enums nullable :(

@chplalex
Copy link

Kotlin Serialization can serialize enum with default value into nonnull property.

@stoichoandreev
Copy link

Yeah GSON is not the best library for parsing JSON data in Kotlin.
Just wanted to post kind of workaround in case you don't like the nullability of you enum property. In this case you can create extension function of your data class and use that extension function when you want to get the value of the enum property, so you avoid dealing with nullability of your property. Something like:

/**
 * @return - the Person occupation if not null or Occupation.UNKNOWN if Person occupation is null
 */
fun Person.getOccupationOrUnknown(): Occupation {
    return when (occupation) {
        null -> Occupation.UNKNOWN
        else -> occupation
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment