Retrofit Response Array or Object either

Viewed 266

In the first case when it returns success true, everything works, the problem when it gets success boolean is false, then the error:

How Retrofit Response Array or Object either.

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 26 path $ .data

Can it be done with one reponse class?

Json response:

{
  "success": true,
  "data": {
    "message": "User created",
  }
}

Json response:

{
  "success": false,
  "data": [
    {
      "code": "existing_user_login",
      "message": "User Exist !"
    }
  ]
}

Code:

public class Response {
    public Boolean success;
    public Data data;

    public Boolean isSuccess() { return success; }

    public Data getData() {
        return data;
    }

    public class Data {
        public String code;
        public String message;
        public String getMessage() { return message; }
        public String getCode() { return code; }
    }
}
2 Answers

Using ObjectMapper you can do it by configuring deserialization features as below:

// import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objMapper = new ObjectMapper();
// this is to accept single element as array
objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
// this is to handle if any property is missing
objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Response resp = objMapper.readValue(jsonString, Response.class);

you could use Object data first, and judge it before use it, like following:

public class Response {
    public Boolean success;
    public Object data;

    public Boolean isSuccess() { return success; }

    public Object getData() {
        if(data instanceof Data){
            //do something
        }else if (data instanceof List) {
            //do something
        }else {
            //do something
        }
        return data;
    }

    public class Data {
        public String code;
        public String message;
        public String getMessage() { return message; }
        public String getCode() { return code; }
    }
}
Related