本文介绍了如果值在OpenAPI生成器的Moshi中不匹配,如何退回枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个枚举类,如果值与任何一个都不匹配,我希望它回退为null.
我正在使用openapi-generator-cli 3.3.0
例如1.生成的类
对象序列化器{@JvmStaticval moshi:Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).add(Unit.javaClass,UnitJsonAdapter()).add(Date :: class.java,Rfc3339DateJsonAdapter().nullSafe()).建造()}数据类GetProfileResponse(@Json(name ="gender")val性别:性别?)枚举类Gender(val值:kotlin.String){@Json(name ="male")male("male"),@Json(name ="female")female("female");}类Api():ApiClient(){fun getProfileResponse():GetProfileResponse {val localVariableBody:kotlin.=空val localVariableQuery:MultiValueMap = mapOf()val contentHeaders:kotlin.collections.Map< kotlin.String,kotlin.String>= mapOf()val acceptsHeaders:kotlin.collections.Map< kotlin.String,kotlin.String>= mapOf(接受"为"application/json")val localVariableHeaders:kotlin.collections.MutableMap< kotlin.String,kotlin.String>= mutableMapOf()localVariableHeaders.putAll(contentHeaders)localVariableHeaders.putAll(acceptsHeaders)val localVariableConfig = RequestConfig(RequestMethod.GET,/轮廓",查询= localVariableQuery,标头= localVariableHeaders)val response = request< GetProfileResponse>(localVariableConfig,localVariableBody)//调用okhttp&在请求()中的moshi(例如Serializer.moshi.adapter(T :: class.java).fromJson(body.source()))当(response.responseType){ResponseType.Success->(响应为Success *).数据为GetProfileResponseResponseType.Informational->去做()ResponseType.Redirection->去做()ResponseType.ClientError->抛出ClientException((响应为ClientError< *>))ResponseType.ServerError->抛出ServerException((响应为ServerError< *>))其他->抛出kotlin.IllegalStateException("Undefined ResponseType.")}}}
- API响应
{性别":"OtherGender"}
运行此代码将导致以下异常:com.squareup.moshi.JsonDataException:预期~~但在路径~~处为"OtherGender"
但是我要性别= null.我该怎么办?
解决方案
class NullableEnumAdapter< T:Enum< T>>:JsonAdapter< T>{@FromJson有趣的fromJson(jsonReader:JsonReader,委托人:JsonAdapter< T>):T?{val value = jsonReader.nextString()返回尝试{委托.fromJsonValue(值)} catch(e:Exception){空值}}}对象序列化器{@JvmStaticval moshi:Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).add(Unit.javaClass,UnitJsonAdapter()).add(Date :: class.java,Rfc3339DateJsonAdapter().nullSafe()).add(Gender :: class.java,NullableEnumAdapter< Gender>()).建造()}
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.")
}
}
}
- 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?
解决方案
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()
}
这篇关于如果值在OpenAPI生成器的Moshi中不匹配,如何退回枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!