androidkotlinmoshiopenapi-generator

How to fallback on a enum if values don't match in OpenAPI generator's Moshi


I have an enum class and would like it to fallback to null if values don't match any of them.

I'm using openapi-generator-cli 3.3.0

e.g. 1. generated class

object Serializer {
    @JvmStatic
    val moshi: Moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .add(Unit.javaClass, UnitJsonAdapter())
            .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
            .build()
}

data class GetProfileResponse (
    @Json(name = "gender") val gender: Gender?
)

enum class Gender(val value: kotlin.String){
    @Json(name = "male") male("male"),
    @Json(name = "female") female("female");
}

class Api() : ApiClient() {
  fun getProfileResponse() : GetProfileResponse {
        val localVariableBody: kotlin.Any? = null
        val localVariableQuery: MultiValueMap = mapOf()

        val contentHeaders: kotlin.collections.Map<kotlin.String,kotlin.String> = mapOf()
        val acceptsHeaders: kotlin.collections.Map<kotlin.String,kotlin.String> = mapOf("Accept" to "application/json")
        val localVariableHeaders: kotlin.collections.MutableMap<kotlin.String,kotlin.String> = mutableMapOf()
        localVariableHeaders.putAll(contentHeaders)
        localVariableHeaders.putAll(acceptsHeaders)

        val localVariableConfig = RequestConfig(
            RequestMethod.GET,
            "/profile",
            query = localVariableQuery,
            headers = localVariableHeaders
        )
        val response = request<GetProfileResponse>(
            localVariableConfig,
            localVariableBody
        )  // call okhttp & moshi (e.g. Serializer.moshi.adapter(T::class.java).fromJson(body.source())) in request()

        return when (response.responseType) {
            ResponseType.Success -> (response as Success<*>).data as GetProfileResponse
            ResponseType.Informational -> TODO()
            ResponseType.Redirection -> TODO()
            ResponseType.ClientError -> throw ClientException((response as ClientError<*>))
            ResponseType.ServerError -> throw ServerException((response as ServerError<*>))
            else -> throw kotlin.IllegalStateException("Undefined ResponseType.")
        }
  }
}
  1. API response
{
  "gender": "OtherGender"
}

Running this code results in the following exception: com.squareup.moshi.JsonDataException: Expected ~~ but was "OtherGender" at path ~~

But I want to gender = null. How can I do it?


Solution

  • class NullableEnumAdapter<T:Enum<T>> : JsonAdapter<T> {
      @FromJson fun fromJson(jsonReader: JsonReader, delegate: JsonAdapter<T>): T? {
        val value = jsonReader.nextString()
        return try {
          delegate.fromJsonValue(value)
        } catch (e: Exception) {
         null
       }
      }
    }
    
    object Serializer {
        @JvmStatic
        val moshi: Moshi = Moshi.Builder()
                .add(KotlinJsonAdapterFactory())
                .add(Unit.javaClass, UnitJsonAdapter())
                .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
                .add(Gender::class.java, NullableEnumAdapter<Gender>())
                .build()
    }