Nitt
Nitt

Reputation: 1923

GSON Parsing - Same key with different type

I am new in gson parsing. I have response

{"data":[23, "Nithinlal P.A"]}

Sometimes I got the response as

{"data":false}

I am using Retrofit 2 Http client library.So I got error while getting the response like this.How I can overcome this issue.

Upvotes: 1

Views: 1324

Answers (1)

W.K.S
W.K.S

Reputation: 10095

If you know what type of data a given request will return, you can use the following approach:

Set the data field to a generic type T in your APIResponse object e.g.

public class APIResponse<T>{
  private T data;
  public T getData();
}

Then, for the first response, you should create a class called User

class User{
   private long id;
   private String name;
}

and add a method to your retrofit api:

@GET("/api/user")    
void getUser(Callback< APIResponse <User>> callback);

For the second response, you would add the method

@GET("/api/status")
void getStatus(Callback< APIResponse <Boolean>> callback);

NOTE At the moment, your first response returns an array with inconsistent types. E.g. the first item is an integer (23) and the second item is a string ("Nithinlal P.A") Your first response should be a JSON object.

Upvotes: 1

Related Questions