Search code examples
androidretrofitsimple-xml-converter

how to parse different xml data in single retrofit call


I am using simplxmlconvertor with retrofit in my app to parse xml response from API. Success response from API is given below.

<Success>
  <id>sf98hjf</id>
</Success>

And error response is given below.

<Error>
  <message>No data found</message>
</Error>

My model class to parse success response is given below

 @Root(name = "Success")
public class ResponseModel {
@Element
private String id;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

}

This works fine when I get success response. But I want to parse error response as well to show error message to user. How can I achieve the same. Now I am getting exception since the structure doesn't match. Thanks in advance.


Solution

  • Finally I found one solution for my question. Instead of trying to parse with 2 different models, I intercepted the response and added a common root element. Then made Success and Error nodes as optional. So whether the response is success or Error the same model will parse it. Code is given below.

    public class XmlInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            String wrappedBody = "<Response>" + body.string() + "</Response>";
            return response.newBuilder()
                    .body(ResponseBody.create(body.contentType(), wrappedBody))
                    .build();
        }
    }
    

    Model class to parse response.

    @Root(name = "Response")
    public class UploadResponseModel {
    @Element(required = false)
    private UploadSuccessModel Success;
    @Element(required = false)
    private ErrorModel Error;
    
    public UploadSuccessModel getSuccess() {
        return Success;
    }
    
    public void setSuccess(UploadSuccessModel success) {
        Success = success;
    }
    
    public ErrorModel getError() {
        return Error;
    }
    
    public void setError(ErrorModel error) {
        Error = error;
    }
    }