【问题标题】:Retrofit POST List of objects and List<MultipartBody.Part>改造 POST 对象列表和 List<MultipartBody.Part>
【发布时间】:2021-02-03 01:01:29
【问题描述】:

改造 2.4.0

retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

我需要在同一个请求中发布对象列表和图片列表,如下所示:

@Multipart
@POST("api/debug/{id}/")
Call<ItemResponse> uploadItems(
        @Path("id") int id,
        @Part("items[]") List<Item> items,
        @Part List<MultipartBody.Part> pictures);

服务器端项目列表未正确序列化:

{
  "items": [
    "{"description":"desc1","id":1,"title":"title1"}",
    "{"description":"desc2","id":2,"title":"title2"}",
    "{"description":"desc3","id":3,"title":"title3"}"
  ],
  "picture1": {
    "name": "picture1",
    "size": "315.777KB"
  },
  "picture2": {
    "name": "picture2",
    "size": "207.821KB"
  }
}

问题似乎在于使用@Part。

有什么诀窍?

【问题讨论】:

    标签: java android serialization retrofit okhttp


    【解决方案1】:

    嗯,你不能直接替换吗 @Part("items[]")@Part?然后你会在 JSON 响应中得到与图片的列表结构相同的结构。

    【讨论】:

    • 如果我这样做会引发错误:@Part 注释必须提供名称或使用 MultipartBody.Part 参数类型。 (参数#2)
    • 好的,我明白了。我认为这个解决方案会对您有所帮助:stackoverflow.com/a/58951111/14056755。 TL;DR 您必须为与 Multipart 对象一起存在的对象列表使用 @PartMap 注释。
    猜你喜欢
    • 2021-03-12
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多