使用Retrofit2发送复杂的对象 [英] Send complex object using Retrofit2

查看:116
本文介绍了使用Retrofit2发送复杂的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Retrofit2和Kotlin将复杂的对象作为请求的参数发送.该对象的结构如下:

I'm trying to send a complex object as a parameter of my request using Retrofit2 and Kotlin. Structure of that object is the following:

{
  "id": "..."
  "token": "..."
  "message": "..."
  "list1": [
    { "id": 1, "value": 2 },
    { "id": 2, "value": 5 }
    //and so on...
  ]
  "list2": [
    { "id": 10, "value": 16 },
    { "id": 11, "value": 21 }
    //and so on...
  ]
  //and so on...
}

列表字段的数量为各种(可以是2个列表,可以是10个)以及每个列表中的项目数.我正在使用以下代码来实现这一目标,之前在我的地图中填充了适当的值:

The number of list fields is various(could be 2 lists, could be 10) as well as the number of items inside each list. I'm using the following code to achieve that, previously filled my Map with the appropriate values:

@JvmSuppressWildcards
@FormUrlEncoded
@POST("get_data.php")
fun getResponse(
    @FieldMap params: Map<String, Any>
): Observable<ResponseModelResult>

由于某种原因,该方法无法正常工作,并且服务器只是忽略了我的参数.我也尝试过将它们作为 @Body 字符串/对象发送,但是服务器似乎仅接受FormUrlEncoded数据.

For some reason that approach is not working properly and the server just ignoring my params. I've also tried to send them as @Body string/object, but it seems like the server accepts only FormUrlEncoded data.

有人可以给我一个例子,如何使用 @FieldMap 方法发送此类数据作为参数吗?

Can someone give me an example how I should send such data as parameter using the @FieldMap approach?

推荐答案

最后,我找到了解决方案.似乎翻新无法处理< String,Any> 映射,因此最简单的方法就是以与Postman类似的方式发送请求参数.

Finally, I found a solution. Seems like retrofit can't deal with the <String, Any> map, so the easiest way would be to send request parameters in a similar way as, for example, in Postman.

val params = mutableMapOf<String, String>()
params["id"] = ...
params["token"] = ...
params["message"] = ...

params["list1[0][id]"] = "${1}"
params["list1[0][value]"] = "${2}"
params["list1[1][id]"] = "${2}"
params["list1[1][value]"] = "${5}"

params["list2[0][id]"] = "${10}"
params["list2[0][value]"] = "${16}"

//and so on

然后,在我的ApiService中:

Then, in my ApiService:

@Headers("Content-Type: application/x-www-form-urlencoded")
@FormUrlEncoded
@POST("get_data.php")
fun getResponse(
    @FieldMap params: Map<String, String>
): Observable<ResponseModelResult>

可能不是整体上最好的方法,但至少对我有用.

Probably, that's not the best approach overall, but at least it works for me.

这篇关于使用Retrofit2发送复杂的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆