Android retrofit converter exception

别来无恙 提交于 2020-01-02 18:56:10

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/19331803/android-retrofit-converter-exception

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