jojemapa
jojemapa

Reputation: 893

Gson deserialize JSON different types (ANDROID)

I'm doing a login. If the data is correct return the following:

{
   "a": 1,
   "b":2,
   "c":3
}

If the data is incorrect return the following:

{
    "status": false,
    "error": {
     .... etc
     }

}

How should my model?... I'm using GSON.

My code:

Gson gson = new Gson();
//As I can get two types of answers, as would my code?
//Model model = gson.fromJson(my_json, Model.class);

Upvotes: 1

Views: 92

Answers (1)

Yasin Kaçmaz
Yasin Kaçmaz

Reputation: 6663

I suggest you this way :

if(responsecode==200){
   Model model = gson.fromJson(my_json, Model.class);
}
else if (responsecode==error){
   AnotherModel anothermodel = gson.fromJson(my_json, AnotherModel.class);
}

Also another way is put all possible response in one Pojo class , like SqueezyMo said in comments :

{
  "a": 1,
  "b":2,
  "c":3,
  "status": false,
  "error": "wrong password"
}

Paste above json example to this site : Json Schema 2 Pojo And generate your Pojo class

Upvotes: 1

Related Questions