Matt Zukowski
Matt Zukowski

Reputation: 4541

Can't post JSON with Retrofit 2

When trying to POST some JSON data using Retrofit 2.0.0-beta4, I'm getting the following error:

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)
...

Not sure what's going on here. As far as I know, my setup is following other presumably working examples verbatim.

My app-level 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'
  ...
}

And my retrofit builder:

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();

Any ideas what I'm doing wrong?

Edit

My API interface looks like this:

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

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

And the API call:

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) {
         ...
     }
});

Upvotes: 2

Views: 2982

Answers (2)

silentsudo
silentsudo

Reputation: 6963

As of today

These are the dependencies

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

Do check here for latest version http://search.maven.org/#artifactdetails%7Ccom.squareup.retrofit2%7Cconverter-gson%7C2.0.1%7Cjar

Upvotes: 2

Matt Zukowski
Matt Zukowski

Reputation: 4541

Looks like my problem was that I had beta3 of the gson converter in my build.gradle, but beta4 of retrofit. Changing my build.gradle to the following made things work:

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

Upvotes: 4

Related Questions