I having the two json response from the server side with the same “key”.The json is posted below

前提是你 提交于 2019-12-04 07:01:24

问题


    {"data":
         {
          "userId":"+919923911289",
          "inTime":"2016-07-25 12:09:47+05:30",
          "outTime":"0",
          "totalTime":"0",
          "type":"attendance"
          }
}

And the second json response is

{"data":"please try again..."}

I am using retrofit to get the response . For the first json i have created the Gson model.But , when the response is in the second json format i didn't have any response model for it.

I am displaying the data using the GsonModel for the first json response. And if there is second type of response what should i do here.Will i use the TypeToken here or something else.

And it also giving me the parsing exception wich i understand.But , i didn't know what i have to do.


回答1:


Create a another model

class ErrorModel{
     String data;
}

and in your main method:

try{
    GsonModel model = gson.fromJson(response,GsonModel.class);
    // ...
}catch(JsonSyntaxException e){
    ErrorModel model = gson.fromJson(response,ErrorModel.class);
    // show error
}



回答2:


if (data.equalsIgnoreCase("please try again...") {
    //show error
} else {
    //do your work with response
}



回答3:


if(data.has("userId") && !data.isNull("userId") ){
    String user_Id=data.getString("userId");
}else{
 ////show message "please try again..." here....
}


来源:https://stackoverflow.com/questions/38561876/i-having-the-two-json-response-from-the-server-side-with-the-same-key-the-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!