[英]Retrofit Moshi Unable to create @Body converter for java.util.HashMap
The line EarthlingsApi.retrofitService.register(params)
行EarthlingsApi.retrofitService.register(params)
in my code below在我下面的代码中
fun clickLogin(){
val params = HashMap<String, String>()
params["email"] = email
params["idToken"] = idToken
viewModelScope.launch {
try {
val userRegisterResult = EarthlingsApi.retrofitService.register(params)
} catch (e: Exception) {
Timber.d("exception? " + e.toString())
_response.value = "Failure: ${e.message}"
}
}
}
will always return the error exception? java.lang.IllegalArgumentException: Unable to create @Body converter for java.util.HashMap<java.lang.String, java.lang.String> (parameter #1) for method ApiService.register
总是会返回错误exception? java.lang.IllegalArgumentException: Unable to create @Body converter for java.util.HashMap<java.lang.String, java.lang.String> (parameter #1) for method ApiService.register
exception? java.lang.IllegalArgumentException: Unable to create @Body converter for java.util.HashMap<java.lang.String, java.lang.String> (parameter #1) for method ApiService.register
And below is the code for EarthlingsApi
下面是EarthlingsApi
的代码
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
interface ApiService {
@POST("/user/register")
suspend fun register(@Body params: HashMap<String, String>?): UserRegister?
}
object EarthlingsApi {
val retrofitService : ApiService by lazy {retrofit.create(ApiService::class.java) }
}
Previously I use Gson and never faced this error.以前我使用 Gson 并且从未遇到过这个错误。 Is there anything else I should do when using Moshi?使用 Moshi 时我还有什么需要做的吗?
It seems Moshi supports fields declared as Map but not as HashMap.似乎 Moshi 支持声明为 Map 但不支持声明为 HashMap 的字段。 So just change the HashMap
inside suspend fun register(@Body params: HashMap<String, String>?): UserRegister?
所以只需改变HashMap
里面的suspend fun register(@Body params: HashMap<String, String>?): UserRegister?
to Map
and it will work.到Map
它将工作。 This answer helped me in solving this, but unfortunately, the questioner there doesn't mark it as an answer.这个答案帮助我解决了这个问题,但不幸的是,那里的提问者没有将其标记为答案。 So maybe anyone later who bumped into this same issue can upvote the answer there.因此,也许以后遇到同样问题的任何人都可以在那里投票。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.