使用Retrofit 2从响应JSON获取单个JSON属性值 [英] Get single JSON property value from response JSON using Retrofit 2

查看:230
本文介绍了使用Retrofit 2从响应JSON获取单个JSON属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Retrofit库(在撰写本文时,版本为2.0.2).

I am using Retrofit library (version 2.0.2 as of this writing).

我正在对响应一个大JSON对象的服务进行GET调用,但我只对其中的一个key:value对感兴趣.

I am making a GET call to a service which responds a big JSON object but I am only interested in one key:value pair in it.

我怎么能得到这个,而不是编写一个与JSON响应匹配的全新POJO类?

How can I get just that instead of writing a whole new POJO class that matches the JSON response?

示例-

{
  status_code: 34,
  status_message: "The resource you requested could not be found.",
  ...,
  ...
}

我只需要状态码值(此处为34).

I need only status code value (34 here).

请注意,我在这里仅提供此JSON对象的示例.我要处理的真正的是巨大的,我只关心其中的一个key:value对.

Please note, I am just giving an example of this JSON object here. The real one I am dealing with is huge and I care about only one key:value pair in it.

谢谢.

推荐答案

您可以参考以下内容:

@GET("/files/jsonsample.json")
Call<JsonObject> readJsonFromFileUri();

class MyStatus{
    int status_code;
}


...
Retrofit retrofit2 = new Retrofit.Builder()
        .baseUrl("http://...")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

WebAPIService apiService = retrofit2.create(WebAPIService.class);
Call<JsonObject> jsonCall = apiService.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
    @Override
    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
        String jsonString = response.body().toString();
        Gson gson = new Gson();
        MyStatus status = gson.fromJson(jsonString, MyStatus.class);
        Log.i(LOG_TAG, String.valueOf(status.status_code));                
    }

    @Override
    public void onFailure(Call<JsonObject> call, Throwable t) {
        Log.e(LOG_TAG, t.toString());
    }
});
...

调试屏幕截图

这篇关于使用Retrofit 2从响应JSON获取单个JSON属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆