如何将改装响应体转换为JsonObject

时间:2016-05-30 11:43:31

标签: android gson retrofit2

public abstract class RetrofitBaseCallBack<T> implements Callback<T> {
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        int responseCode = response.code();
        if (responseCode == Constants.ServerResponse.Code.STATUS_OK
                || responseCode == Constants.ServerResponse.Code.STATUS_CREATED_SUCCESS
                || responseCode == Constants.ServerResponse.Code.STATUS_IN_PROGRESS
                || responseCode == Constants.ServerResponse.Code.STATUS_NO_CONTENT
                || responseCode == Constants.ServerResponse.Code.STATUS_ACCEPTED) {
            // i want to navigate to onResponseSuccess when "success":true
            onResponseSuccess(call, response);
        } else {
           //i want to navigate to onResponseFailure when "success":false
            onErrorResponse(call, response);
        }
    }
    }

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

    public abstract void onResponseSuccess(Call<T> call, Response<T> response);

    public abstract void onResponseFailure(Call<T> call, Response response, String message);

    public abstract void onRetrofitBaseCallBackFailure(Call<T> call, Throwable t);
}

我通过扩展改造回调来上课。我想将响应解析为字符串。在我的例子中,每个响应都获取此类型的JSON对象。在成功回应的情况下:

{
  "success": true,
  "abc": {
    "a": 0.15,
    "b": "Better Exchange Rate",
  }
}

如果失败回应

{
      "success": false,
      "abc": {
        "a": 0.15,
        "b": "Better Exchange Rate",
      }
    }

如何将响应体转换为JsonObject,以便我可以检查字段“成功”:并导航相应的方法,即 onResponseSuccess(呼叫,响应响应)以防万一成功, onResponseFailure(来电,响应回复,字符串信息)以防万一

1 个答案:

答案 0 :(得分:0)

如何在改造中从response.body()获取JSONObject:

try {

    JSONObject jsonObj = new JSONObject(response.body().toString());

} catch (JSONException e) {

    e.printStackTrace();
    Log.d("TAG", "No valid json");

}