1

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.

Nitt
  • 1,813
  • 3
  • 12
  • 15
  • this looks for Retrofit-1 , not sure if this will work to Retrofit-2 http://stackoverflow.com/questions/24279245/how-to-handle-dynamic-json-in-retrofit – Yazan Nov 07 '16 at 08:06

1 Answers1

1

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.

W.K.S
  • 9,787
  • 15
  • 75
  • 122
  • 1
    i don't think that OP is able to determine when it will be object or not, i think it's based on the request result (unpredictable) – Yazan Nov 07 '16 at 08:07
  • @W.K.S I can't predit the which type of response receive. So How can I call this – Nithinlal Nov 07 '16 at 08:13
  • @Nithinlal: Yazan has linked an answer for that scenario in his comment – W.K.S Nov 07 '16 at 19:17