Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

471
Visualizações
json Enum deserialization breakes kotlin null-safety

I use Kotlin data classes and GSON to deserialize JSON schemas, and implement default values to protect against null-objects in JSON. Also- JSON int enums map to Kotlin enum values using the @SerializedName annotation:

data class Person(@SerializedName("name")
           val name: String = ",
           @SerializedName("age")
           val age: Int = 0,
           @SerializedName("hairColor")
           val hairColor: Color = Color.NONE)

enum class Color{
    @SerializedName("1")
    BROWN,
    @SerializedName("2")
    BLONDE,
    NONE
}

Focusing on enum deserialization- this works well for situations when a field matches a known enum or if the field is totally absent from the JSON, in which case the default enum will be implemented.

BUT - if the received enum in JSON doesn't map to a known enum value in my kotlin enum - the resulting deserialized enum will be null!!

{"name":"Joe","age":10,"hairColor":1} ->
Person(name=Joe, age=10, hairColor=BROWN)

{"name":"Jim"} ->
Person(name=Jim, age=0, hairColor=NONE)

{"name":"Jeff", "age":8,"hairColor":3) ->
Person(name=Jane, age=8, hairColor=null)

Gson fools the null safety mechanism of Kotlin by assigning null to a non-null type. The question - how to map un-known JSON enums to deafult Kotlin enums? My goal is to maintain null-safety with simple implementation.

P.S. - I know I could just parse JSON enums as Ints, and deserialize them later, or use backing fields and custom getters, but I like the elegance and type-safety parsing directly to Kotlin enums.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I wrote a Kotlin wrapper (called it Arson) for Gson that adds missing default values to the deserialized objects. On top of that it also checks for null values that violate the Kotlin non-null safety.

Check it out: https://github.com/taskbase/arson

Use it in your project:

<dependency>
    <groupId>com.taskbase.arson</groupId>
    <artifactId>arson</artifactId>
    <version>1.0</version>
</dependency>

class ArsonTest {

    @Test
    fun testEnumDeserialization() {
        val json = "{'name':'Jim', 'hairColor':'3'}"

        // Gson deserializes the value to null
        val p1 = Gson().fromJson(json, Person::class.java)
        assertNull(p1.hairColor)

        // The wrapper replaces null with the default value
        val p2 = Arson(gson = Gson()).fromJson(json, Person::class.java)
        assertEquals(Color.NONE, p2.hairColor)
    }
}

data class Person(
    val name: String = "",
    val age: Int = 0,
    val hairColor: Color = Color.NONE
)

enum class Color {
    @SerializedName("1")
    BROWN,
    @SerializedName("2")
    BLONDE,
    NONE
}

I was struggling with Gson's lack of Kotlin support as well. Gson is a Java library and does not understand the type system of Kotlin. I tested several other JSON libraries but none worked well enough. I therefore wrote a function that is using the Kotlin reflection library to create a deep copy of an object that adds missing default values.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda