无法使用Retrofit 2发布JSON

时间:2016-02-06 23:20:36

标签: android json retrofit2

使用Retrofit POST尝试2.0.0-beta4某些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) {
         ...
     }
});

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

截至今天

这些是依赖项

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

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