gpt4 book ai didi

android - 如何处理改造中的两种不同响应

转载 作者:行者123 更新时间:2023-12-02 16:26:34 24 4
gpt4 key购买 nike

我关注了this使用 Retrofit2 POST 数据

我用过JSON POJO解析我的 POST 和 GET 文件

所以如果记录中的数据存在,我会得到这种响应

{
"status": "200",
"response": [{
"cnt_id": "201",
"phn_no": "3251151515",
"dat_cnt": "Reset Password request Said to Mail"
},
{
"cnt_id": "209",
"phn_no": "555465484684",
"dat_cnt": "Hi DEMO User , Congratulations! Your account has been created successfully."
},
{
"cnt_id": "210",
"phn_no": "4774748",
"dat_cnt": "Hi XYZ , Congratulations! Your account has been created successfully."
}
]
}

如果没有数据我会得到

{"status":"204","re​​sponse":{"msg":"无内容"}}
{"status":"400","re​​sponse":{"msg":"BadRequest"}}
{"status":"401","re​​sponse":{"msg":"未经授权的用户"}}

所以在这里我可以解析状态 200 中的数据,但是当状态不等于 200 时我想处理它们

我尝试过

   status = response.body().getStatus();
if(status.equals("200")) {
List<Response> resList = response.body(). getResponse();

for(int i = 0; i<resList.size(); i++)
{.
.
..
.
}
}

else {
//not Implemented
}

现在我应该写什么,否则我在 POJO 中使用了响应数据,它不等于 200,但我要求列表

更新

com.example.Example.java

public class Example {
@SerializedName("status") @Expose private String status;
@SerializedName("response") @Expose private List<Response> response = null;
}

com.example.Response.java

public class Response {
@SerializedName("cnt_id") @Expose private String cntId;
@SerializedName("phn_no") @Expose private String phnNo;
@SerializedName("dat_cnt") @Expose private String datCnt;
}

最佳答案

public class Example {
@SerializedName("status") @Expose private String status;
@SerializedName("response") @Expose private Object response = null;
}

public class Response {
@SerializedName("cnt_id") @Expose private String cntId;
@SerializedName("phn_no") @Expose private String phnNo;
@SerializedName("dat_cnt") @Expose private String datCnt;
}

public class ResponseError{
@SerializedName("msg") @Expose private String msg;
}

你的回调方法应该是这样的

new Callback<Example>() {
@Override
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.isSuccessful()){
Example example = response.body();
Gson gson = new GsonBuilder().create();

if (example.status.equals("200")) {
TypeToken<List<Response>> responseTypeToken = new TypeToken<List<Response>>() {};
List<Response> responseList = gson.fromJson(gson.toJson(example.getResponse()), responseTypeToken.getType());
} else {
//If for everyOther Status the response is Object of ResponseError which contains msg.
ResponseError responseError = gson.fromJson(gson.toJson(example.getResponse()), ResponseError.class);
}
}
}

@Override
public void onFailure(Call<Example> call, Throwable t) {
//Failure message
}
}

关于android - 如何处理改造中的两种不同响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51238140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com