k

    kierans777

    7 months ago
    I feel like I'm missing something obvious when trying to deserialise some JSON into an enum. Due to some developers not reading the spec properly, the server returns some JSON that is keyed incorrecty, and is lowercase.
    {
      "healthCheck": "success"
    }
    I need to parse it into an object of
    HealthCheck
    @Serializable
    data class HealthCheck(
      @SerialName("healthCheck")
      @Serializable(with = StatusSerializer::class)
      val result: Status
    ) {
      @Serializable
      enum class Status {
        SUCCESS
      }
    }
    
    object StatusSerializer : JsonTransformingSerializer<HealthCheck.Status>(HealthCheck.Status.serializer()) {
      override fun transformDeserialize(element: JsonElement): JsonElement {
        val el = super.transformDeserialize(element)
    
        return JsonPrimitive(el.toString().uppercase())
      }
    }
    However I get an exception
    HealthCheck.Status does not contain element with name '"SUCCESS"'
    Emil Kantis

    Emil Kantis

    7 months ago
    Tried adding
    @SerialName("success")
    on the enum value?
    k

    kierans777

    7 months ago
    Thanks @Emil Kantis for the suggestion. It doesn't work with
    @SerialName("success")
    or
    @SerialName("SUCCESS")
    Emil Kantis

    Emil Kantis

    7 months ago
    you would need to remove the
    with = StatusSerializer::class)
    also.
    k

    kierans777

    7 months ago
    Success! (pun intended)
    Thanks
    Emil Kantis

    Emil Kantis

    7 months ago
    you’re welcome 🙂