【问题标题】:How to get simple JSON object in Retrofit 2.0.0 beta 1?如何在 Retrofit 2.0.0 beta 1 中获取简单的 JSON 对象?
【发布时间】:2015-09-23 00:11:23
【问题描述】:

我正在尝试转换这个看起来像这样的简单响应

{
  "field_one": "bearer",
  "field_two": "fgh",
  "field_three": 0
}

我正在使用最新版本的 Retrofit 2.0.0-beta1。我以前从未使用过改造。有很多旧版 Retrofit 的教程和示例。我尝试了适用于旧版本的不同技术,但不适用于最新版本。由于缺少最新版本 Retrofit 的文档,我找不到解决方案。

我想使用最新版本。

这里是 POJO

public class Auth {
    @SerializedName("field_one")
    @Expose
    private String fieldOne;

    @SerializedName("field_two")
    @Expose
    private String fieldTwo;

    @SerializedName("field_three")
    @Expose
    private Integer fieldThree;

    // setter and getter etc. etc. 
}

这是我正在使用的界面

interface Authorization {
   @Headers("Authorization: This is some header")
   @GET("api/v1/mytoken")
   Call<Auth> getToken();
}

这就是我调用服务的方式

  OkHttpClient client = new OkHttpClient();

  Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://myendpoint.com/")
            .client(client)
             .addConverterFactory(GsonConverterFactory.create())
            .build();

    Authorization serviceAuthorization = retrofit.create(Authorization.class);
    serviceAuthorization.getToken().enqueue(new Callback<Auth>() {
        @Override
        public void onResponse(Response<Auth> response) {
            Log.d("Response", ">>> "+ response.toString());
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d("fail", ">>> "+ t.getMessage());
        }
    });

我无法获得输出。它只是打印这个

Response: >>> retrofit.Response@2567e2c3

我想在稍后使用的 Auth Object 中获取数据。

请给我最好的解决方案

谢谢!

【问题讨论】:

  • 你有什么问题?您收到编译器消息吗?运行时错误?
  • 没有错误。我更新了我得到什么输出和我想要什么的问题

标签: android json retrofit


【解决方案1】:

我猜你没有看到你期望看到你的对象打印在这一行——

Log.d("Response", ">>> "+ response.toString());

这将在响应上调用toString 方法。如果你想在你的反序列化对象上调用它,首先调用body()方法 --

if(response.isSuccess()) {
    Log.d("Response", ">>> "+ response.body().toString());
} else {
    Log.d("Response", "Error - " + response.code())
} 

【讨论】:

  • 使用 response.toStirng() 我得到Response: &gt;&gt;&gt; retrofit.Response@2567e2c3 但是当我使用 response.body().toString() 我得到NullPointerException
  • 我也试过 response.raw().toString() 现在我得到了这个 Response{protocol=http/1.1, code=404, message=Not找到了,url=myendpoint.com/api/v1/oauth2/token}
  • 这有帮助 - 404 是未找到,因此您没有调用正确的端点。
  • 是的,您的通话有问题导致您收到 404。请参阅我的编辑以避免 NPE。如果您想要错误响应的文本,您也可以在响应上调用errorBody(),但它可能只是“未找到”的一些变体
  • 我在 [link] (square.github.io/retrofit) 中的文档中提供 Headers 。我还尝试在 Intercepter 中给出标题。但同样的 404 响应
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多