'moshi adapter toJson converts to string instead of object
Below is my code
val itemsInCart = viewModelScope.async {
cartItemRepository = CartItemRepository()
cartItemRepository?.getItemsInCartBySellerSuspend(email, sellerPK)
}
val getItemsInCart = itemsInCart.await()
val moshi = Moshi.Builder().add(BigDecimalAdapter).add(KotlinJsonAdapterFactory()).build()
val tempListItemsInCart = Types.newParameterizedType(List::class.java, CartItem::class.java)
val moshiAdapterForItemsInCart = moshi.adapter<List<CartItem>>(tempListItemsInCart)
val itemsInCartJson = moshiAdapterForItemsInCart.toJson(getItemsInCart)
Code above retrieves list of CartItem from db. CartItem contains BigDecimal, hence the usage of BigDecimalAdapter.
I passed itemsInCartJson to params["items"] = itemsInCartJson. Here I thought itemsInCartJson is supposed to be json object, but actually it was passed as String.
Here's how items was passed, as per retrofit's log
{"items":"[{\"id\":1,\"email\":\"[email protected]\",\"productId\":4,\"productPK\":\"BUSINESS#[email protected]\",\"productSK\":\"PRODUCT#f89tlW1ihl\",\"sku\":\"SK67\",\"name\":\"dekonh\",\"unitPrice\":\"20\",\"quantity\":3,\"totalPrice\":\"60\",\"hoursNeededToPrepare\":0,\"discountCode\":\"\"},{\"id\":2,\"email\":\"[email protected]\",\"productId\":5,\"productPK\":\"BUSINESS#[email protected]\",\"productSK\":\"PRODUCT#yt0TjnnCdD\",\"sku\":\"SKP8\",\"name\":\"First+product\",\"unitPrice\":\"1.7\",\"quantity\":2,\"totalPrice\":\"3.4\",\"hoursNeededToPrepare\":3,\"discountCode\":\"\"}]","pickUpBy":"fr"}
If it helps, here's how I build my retrofit
private val moshi = Moshi.Builder()
.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()
Where did I do wrong? items in my backend expected object and not string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
