使用 Retrofit 2 从响应 JSON 中获取单个 JSON 属性 值
Get single JSON property value from response JSON using Retrofit 2
我正在使用 Retrofit 库(撰写本文时为 2.0.2 版)。
我正在对响应大 JSON 对象的服务进行 GET 调用,但我只对其中的一对 key:value 感兴趣。
我怎样才能得到它而不是编写一个与 JSON 响应匹配的全新 POJO class?
示例 -
{
status_code: 34,
status_message: "The resource you requested could not be found.",
...,
...
}
我只需要状态码值(这里是34)。
请注意,我只是在此处给出此 JSON 对象的示例。我要处理的真货很大,我只关心其中的一对 key:value。
提前致谢。
您可以参考以下内容:
@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.0.2 版)。
我正在对响应大 JSON 对象的服务进行 GET 调用,但我只对其中的一对 key:value 感兴趣。
我怎样才能得到它而不是编写一个与 JSON 响应匹配的全新 POJO class?
示例 -
{
status_code: 34,
status_message: "The resource you requested could not be found.",
...,
...
}
我只需要状态码值(这里是34)。
请注意,我只是在此处给出此 JSON 对象的示例。我要处理的真货很大,我只关心其中的一对 key:value。
提前致谢。
您可以参考以下内容:
@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());
}
});
...
调试截图