简体   繁体   中英

Retrofit Response

So i have this JSON Response from a server:

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

And a java class where:

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

And here is where i call the service:

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

And i want to be able to get the value of the id when there is a response from server. How do i go about this? Please Help

Change you JSONResponse as below; because JSON you're getting has 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;
}

}

Result Class

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;
}

}

Change your code as

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM