我有一个枚举类,并且如果值与任何一个都不匹配,希望它回退为null。

我正在使用openapi-generator-cli 3.3.0

例如
1.生成类

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.")
        }
  }
}
  • API响应
  • {
      "gender": "OtherGender"
    }
    

    运行此代码将导致以下异常:
    com.squareup.moshi.JsonDataException:预期~~但在路径~~处为“OtherGender”

    但是我想性别= null。我该怎么做?

    最佳答案

    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()
    }
    

    关于android - 如果值在OpenAPI生成器的Moshi中不匹配,如何退回枚举,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60071108/

    10-10 20:01