【问题标题】:Can't post JSON with Retrofit 2无法使用 Retrofit 2 发布 JSON
【发布时间】:2016-02-06 23:20:35
【问题描述】:

当尝试使用 Retrofit 2.0.0-beta4 POST 一些 JSON 数据时,我收到以下错误:

java.lang.IllegalArgumentException: Unable to create @Body converter for class my.pojos.Credentials

...

Caused by: java.lang.IllegalArgumentException: Could not locate RequestBody converter for class my.pojos.Credentials.
Tried:
* retrofit2.BuiltInConverters
* retrofit2.GsonConverterFactory
  at retrofit2.Retrofit.nextRequestBodyConverter(Retrofit.java:288)
...

不确定这里发生了什么。据我所知,我的设置是逐字遵循其他可能有效的示例。

我的应用级build.gradle

dependencies {
  ...
  compile 'com.google.code.gson:gson:2.5'
  compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
  compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
  compile 'com.squareup.okhttp:okhttp:2.7.0'
  ...
}

还有我的改造建造师:

Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(context.getString(R.string.rest_url))
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

任何想法我做错了什么?

编辑

我的 API 接口如下所示:

import retrofit2.Call;
import retrofit2.http.*;

public interface MyRestApi {
    @POST("/auth")
    Call<Auth> login(@Body Credentials user);
}

以及 API 调用:

Call<Auth> authCall = retrofit.create(MyRestApi.class).login(creds);

authCall.enqueue(new Callback<Auth>() {
     @Override
     public void onResponse(Call<Auth> call, Response<Auth> response) {
         ...
     }

     @Override
     public void onFailure(Call<Auth> call, Throwable t) {
         ...
     }
});

【问题讨论】:

    标签: android json retrofit2


    【解决方案1】:

    看来我的问题是我的build.gradle 中有beta3 的gson 转换器,但是beta4 的改造。将我的 build.gradle 更改为以下内容即可:

    dependencies {
        compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
        compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    }
    

    【讨论】:

      【解决方案2】:

      从今天开始

      这些是依赖项

      compile 'com.squareup.retrofit2:converter-gson:2.0.1'
      

      请在此处查看最新版本 http://search.maven.org/#artifactdetails%7Ccom.squareup.retrofit2%7Cconverter-gson%7C2.0.1%7Cjar

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 2013-10-06
        • 2021-08-18
        • 2017-07-01
        相关资源
        最近更新 更多