Get single JSON property value from response JSON using Retrofit 2

青春壹個敷衍的年華 提交于 2019-12-11 00:47:37

问题


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

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.

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

Example -

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

I need only status code value (34 here).

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.

Thanks in advance.


回答1:


You can refer to the following:

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

and

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

Debug screenshot



来源:https://stackoverflow.com/questions/37221570/get-single-json-property-value-from-response-json-using-retrofit-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!