处理不同的改造响应

时间:2020-05-27 21:44:03

标签: java android gson retrofit2

我知道这个问题已经问了很多,但是我所见的答案都没有帮助我澄清这个问题。 除了具体的答案之外,我还需要更多方法准则。

问题...

我会从我的网络服务中收到下一个答案,具体取决于是否建立了某些用户:

{
    "ok": [
        {
            "id": 1,
            "username": "test",
            "pass": "123",
            "reg_date": "2020-05-27 00:00:00"
        }
    ]
}

和...

{
    "error": [
        {
            "message": "No such user"
        }
    ]
}

如果我对这个定义有误,请纠正我:这两个对象都是以String作为键和array作为值,以及{{1 }},可以是任意长度,在这种情况下,其类型为array

因此,正如您可能已经猜到的,我需要根据情况从此响应中获取特定的值,甚至是object值(“ ok”或“ error”),并在某些TextView中显示类似:

好吧, ID:1

错误, 没有这样的用户

到目前为止,我一直在尝试为接收到的列表中的每个对象创建一个类:

key
public class EntityUser {
    @SerializedName("id")
    private int id;
    @SerializedName("username")
    private String username;
    @SerializedName("pass")
    private String password;
    @SerializedName("reg_date")
    private String registerDate;

    //Getters and constructor...
}

还有一个Api,我认为这是问题所在:

public class EntityError {
    @SerializedName("message")
    private String message;

    //Getters and constructor...
}

如上所述,我想我得到的响应是执行public interface JsonApi { @GET("SelectUser.php") Call<Map<String, List>> getGenericResponse(); } 时的Map<String, List>,但是我不知道如何处理它,所以我可以我希望的值:

Call

正如我在代码中所写的那样,我需要根据Gson gson = new GsonBuilder().setLenient().create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://192.168.0.35/app_android/webservices/") .addConverterFactory(GsonConverterFactory.create(gson)) .build(); JsonApi jsonApi = retrofit.create(JsonApi.class); Call<Map<String, List>> call = jsonApi.getGenericResponse(); call.enqueue(new Callback<Map<String, List>>() { @Override public void onResponse(Call<Map<String, List>> call, Response<Map<String, List>> response) { if(response.isSuccessful()){ if (response.body().containsKey("ok")){ //Here i need to create instance of EntityUsr so I can bind the values to his vars }if(response.body().containsKey("error")){ //Shows an error message according to the message value } } } @Override public void onFailure(Call<Map<String, List>> call, Throwable t) { prueba.setText("Error: " + t.getMessage()); } }); 从Web服务带来的答案来创建相应对象的实例,以便从中获取特定的值。

我该怎么做?

考虑到翻新的可用性,我是否迷失了自己的方法?

我不想改变从网络服务接收到的json的结构

提前谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用简单的方法代替将其解析为Map<String, List>

  1. 声明对象UserResponse
public class UserResponse {
    @SerializedName("ok")
    private ArrayList<EntityUser> users;
    @SerializedName("error")
    private ArrayList<EntityError> errors;
}
  1. 将您的API调用更改为此
public interface JsonApi {
    @GET("SelectUser.php")
    Call<UserResponse> getGenericResponse();
}
  1. 获取成功时处理响应
if (response.body().getUsers() != null){
   // return list users
}if(response.body().getErrors != null){
   // return list errors
}