Question

How to format/design your class if you can get 2 different response request from the server?

Note: Retrofit will thrown an Exception if the JSON response format (design) is different with your class. All fields from JSON response must be present in your class.

Java class, like JSON response:

public class RequestResponseLogin
{
   public ResponseLogin status;

   public class ResponseLogin
   {
      public boolean success;
      public List<String> message;
   }
}

The JSON response:

{
    "status" : {
                    "success" : false
                    "message" : {
                                    "Invalid credientials",
                                    "....",
                                    "...."
                                }
                }
}

This is how I request the response:

interface iLogin
{
   @GET
   RequestResponseLogin loginUser(@Query("user") String user, @Query("pass") String pass);
}

// ....
RequestResponseLogin response = data.loginUser("admin", "abc123");

If the login failed, then public List<String> message; will be populated with messages from the web server:

message[0] = 'Invalid credentials';
message[1] = 'Invalid username';
message[2] = 'Password match correct';

But if the web server does not reply anything (success login), than I get an exception by retrofit, because public List<String> message; is empty, the web server replied with a simple empty string message and not with a string array. It would work if I change public List<String> message; to public String message;, but I can't because if the login fails, it must be a string array.

Was it helpful?

Solution

This has nothing to do with Retrofit. Gson is used to deserialize JSON responses by default.

Since your server sends back inconsistent JSON structure, you should use a custom TypeAdapter on a Gson instance to handle this.

After creating your Gson instance (as "gson" in this example), you can pass it to Retrofit like this:

RestAdapter ra = new RestAdapter.Builder()
    // ... normal stuff ...
    .setConverter(new GsonConverter(gson))
    .build();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top