改造响应

时间:2018-11-15 05:39:38

标签: android retrofit

所以我有来自服务器的JSON响应:

{
    "result": {
        "id": 30,
        "status": "Successful."
    }
}

还有一个Java类,其中:

public class JSONResponse {
    @SerializedName("result")
    public JsonObject res;
    @SerializedName("id")
    public int id;
    @SerializedName("status")
    public String msg;
}

这是我给该服务打电话的地方:

customerResponseCall.enqueue(new Callback<CustomerRequestResponse>() {
            @Override
            public void onResponse(Call<CustomerRequestResponse> call, Response<CustomerRequestResponse> response) {
               response.body().res.get(String.valueOf(response.body().id));
                Toast.makeText(MainActivity.this, "User Registed Successfully!!!" + "\n" + "User ID = " + response.body().id, Toast.LENGTH_LONG).show();// this  your result

            }

            @Override
            public void onFailure(Call<CustomerRequestResponse> call, Throwable t) {
                Log.e("response-failure", call.toString());
            }
        });

当服务器有响应时,我希望能够获得id的值。我该怎么办?请帮助

1 个答案:

答案 0 :(得分:1)

如下更改您的JSONResponse;因为您获取的JSON具有JSONObject result

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class CustomerRequestResponse{

@SerializedName("result")
@Expose
private Result result;

public Result getResult() {
return result;
}

public void setResult(Result result) {
this.result = result;
}

}

结果类

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Result {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("status")
@Expose
private String status;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

}

将代码更改为

customerResponseCall.enqueue(new Callback<CustomerRequestResponse>() {
            @Override
            public void onResponse(Call<CustomerRequestResponse> call, Response<CustomerRequestResponse> response) {
                Integer id =  response.body().getResult().getId();
                Toast.makeText(MainActivity.this, "User Registered Successfully!!!" + "\n" + "User ID = " + id, Toast.LENGTH_LONG).show();// this  your result

            }

            @Override
            public void onFailure(Call<CustomerRequestResponse> call, Throwable t) {
                Log.e("response-failure", call.toString());
            }
        });