2016-03-03 129 views
2

我希望有人能帮助我。Retrofit 2.0无法将请求正文转换为JSON

我尝试使用Retrofit 2.0发送带有JSON正文的POST请求。

接口:

public interface Interface { 
    @POST(/*path*/) 
    Call<MyResponseObject> sendInt(@Body MyInteger myInt); 
} 

MyInteger类:

public class MyInteger { 
    int id; 

    public MyInteger(int id) { 
     this.id = id; 
    } 
} 

MainActivity的部分:

private Retrofit mRetrofit = null; 
private final Interface mService; 
... 
... 
mRetrofit = new Retrofit.Builder() 
       .baseUrl(/*URL*/) 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 
mService = mRetrofit.create(Interface.class); 

召唤:

MyInteger id = new MyInteger(0); 
mService.sendInt(id).enqueue(new Callback<MyResponseObject>() { 
    @Override 
    public void onResponse(Call<MyResponseObject> call, Response<MyResponseObject> response) {/*Log something*/} 

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

在我看来是这样的例子: https://futurestud.io/blog/retrofit-send-objects-in-request-body

但GsonConverter不能MyInteger转换成JSON .. 下面是日志:

java.lang.IllegalArgumentException: Unable to create @Body converter for class com.??.MyInteger (parameter #1) 
                            for method Interface.sendInt 
... 
... 
Caused by: java.lang.IllegalArgumentException: Could not locate RequestBody converter for class com.??.MyInteger. 
                          Tried: 
                           * retrofit2.BuiltInConverters 
                           * retrofit2.GsonConverterFactory 
                           at retrofit2.Retrofit.nextRequestBodyConverter(Retrofit.java:288) 
                           at retrofit2.Retrofit.requestBodyConverter(Retrofit.java:248) 
                           at retrofit2.RequestFactoryParser.parseParameters(RequestFactoryParser.java:491) 
+0

我的解决方法是发送改装的RequestBody对象,而不是我自己的myInteger的对象。 Gson gson = new Gson(); 字符串json = gson.toJson(myIntegerObject); RequestBody requestBody = RequestBody.create(MediaType.parse(“application/json”),josn); – nast

+0

您需要为MyInteger类生成getter和setter,或者使int id为public。 – vbp

回答

3

我有同样的问题。根本原因是我使用的是不兼容的库。

这种组合适用于我:现在

<dependency> 
     <groupId>com.squareup.retrofit2</groupId> 
     <artifactId>retrofit</artifactId> 
     <version>2.0.0-beta4</version> 
    </dependency> 
    <dependency> 
    <groupId>com.google.code.gson</groupId> 
     <artifactId>gson</artifactId> 
     <version>2.6.2</version> 
    </dependency> 
    <dependency> 
     <groupId>com.squareup.retrofit2</groupId> 
     <artifactId>converter-gson</artifactId> 
     <version>2.0.0-beta4</version> 
    </dependency> 
+0

我使用与gradle相同的依赖关系: compile'c​​om.squareup.retrofit2:retrofit:2.0.0-beta4' compile'c​​om.squareup.retrofit2:converter-gson:2.0.0-beta3' compile' com.google.code.gson:gson:2.6.2' – nast

+0

接下来我要做的是在调试器中逐步调试过程,并尝试理解失败的原因。您也可以在不同的环境中尝试,例如使用较新的Java版本。我看不出你的代码有什么问题。 (但是,我是新的Retrofit,现在我正在同步使用它,因此不要将其作为全面的代码审查)。 – jgaa

+0

你救了我的一天! – Smiderle