Reputation: 4578
The line 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
And below is the code for 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. Is there anything else I should do when using Moshi?
Upvotes: 1
Views: 1518
Reputation: 4578
It seems Moshi supports fields declared as Map but not as HashMap. So just change the HashMap
inside suspend fun register(@Body params: HashMap<String, String>?): UserRegister?
to Map
and it will work. 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.
Upvotes: 2