![](/img/trans.png)
[英]Mapping map to a list of objects which contains a name and a value parameter
[英]how to give model class as parameter in retrofit which contains list of objects,
{
"cartItems":[
{
"product":"2",
"productType":"3",
"qty":"50",
"unit":"BAGS"
},
{
"product":"1",
"productType":"2",
"qty":"50",
"unit":"BAGS"
}
]
}
//這種類型的JSON必須作為參數給出,所以請任何人幫忙清除它,提前謝謝。
這比你想象的要容易。 你只需要先制作一個 model class 。 然后創建一個 post 方法以在您的請求中傳遞該 model class 。
例如,在您的情況下:
Model class:
public class CartModel { @SerializedName("cartItems") ArrayList<CartItemsModel> cartItems; public ArrayList<CartItemsModel> getCartItems() { return cartItems; } public void setCartItems(ArrayList<CartItemsModel> cartItems) { this.cartItems = cartItems; } public static class CartItemsModel { @SerializedName("product") String product; @SerializedName("qty") int qty; @SerializedName("BAGS") String unit; public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } }
}
API 接口:
//This is just for understanding, your method can be different according to //your API structure. @POST("your-api-link") // excluding the base URL @FormUrlEncoded Call<CartModel> getUserRegistration(@Body CartModel cartModel);
有很多資源可以自動生成 model 類。
https://json2csharp.com/json-to-pojo
https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-
這是 kotlin:
data class CarItemList(
@SerializedName("cartItems")
val cartItems: List<CartItem>?
)
data class CartItem(
@SerializedName("product")
val product: String?,
@SerializedName("productType")
val productType: String?,
@SerializedName("qty")
val qty: String?,
@SerializedName("unit")
val unit: String?
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.