'No JsonAdapter for java.util.LinkedHashMap using moshi

Running this code

val itemsInCart = viewModelScope.async {
    cartItemRepository = CartItemRepository()
    cartItemRepository?.getItemsInCartBySellerSuspend(email, sellerPK)
}
val setItems = arrayListOf<JSONObject>()
val getItemsInCart = itemsInCart.await()
if (getItemsInCart != null) {
    for (items in getItemsInCart){
        val newCartItem = CartItem()
        newCartItem.id = items.id
        newCartItem.email = items.email
        newCartItem.productId = items.productId
        setItems.add(newCartItem.toJSON())
    }
}

val params = HashMap<String, Any>()
params["PK"] = userPK
params["items"] = setItems
val getSubmitStatus = EarthlingsApi.retrofitService.userOrderSubmit(params)

will throw the error No JsonAdapter for java.util.LinkedHashMap<java.lang.String, java.lang.Object>, you should probably use Map instead of LinkedHashMap (Moshi only supports the collection interfaces by default) or else register a custom JsonAdapter.

Here's how I build my Moshi and Retrofit

private val moshi = Moshi.Builder()
    .add(LinkedHashMapAdapter())
    .add(BigDecimalAdapter)
    .add(KotlinJsonAdapterFactory())
    .build()
private val retrofit = Retrofit.Builder()
    .addConverterFactory(ScalarsConverterFactory.create())
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .addCallAdapterFactory(NetworkResponseAdapterFactory())
    .baseUrl(BASE_URL)
    .client(client)
    .build()

@POST("/user/order/submit")
suspend fun userOrderSubmit(@Body params: Map<String, Any>?): NetworkResponse<OrderSubmitResponse, ErrorResponse>

As you can see, I have already created the LinkedHashMapAdapter (below is the code), but it will still return the above error. So either I made something wrong in my LinkedHashMapAdapter code below or somewhere else

class LinkedHashMapAdapter {
    @ToJson
    fun arrayListToLinkedHashMap(list: LinkedHashMap<String,Any>): LinkedHashMap<String,Any> = list

    @FromJson
    fun arrayListFromLinkedHashMap(list: LinkedHashMap<String,Any>): LinkedHashMap<String,Any> = list
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source