I am using retrofit for android has been working great but I was wondering if there is a better solution to my problem.
Background
So I have a backend server which may respond with a server related error message in JSON form (not network) like "could not find ID X" etc.
It looks like this
{
"data": {
"errors": {
"base": [
"You could do the following because of blah blah"
]
}
}
}
So the problem is the JSON error object which contains the array "base" might NOT be called "base" it could be called something else completely different. My backend has many kind of error response message name which cannot be changed so easily.
My question, it is possible to deserializise this JSON array without having to know its name in advance.
So far I have been doing this which is becoming a pain.
public class MyRetrofitError
{
@SerializedName(JsonConstants.ERROR_KEY)
private Errors errors;
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
public static class Errors
{
private String errorMessage;
private ErrorCodes errorCodes;
public enum ErrorCodes{
BOOKED_OVER_20,PROMO_CODE_FAILED;
}
@SerializedName("booked_over")
private ArrayList<String> bookedOver= new ArrayList<String>();
@SerializedName("promo_fail")
private ArrayList<String> promoFailed= new ArrayList<String>();
public String getErrorMessage() {
if(promoFailed!= null && promoFailed.size() > 0) {setErrorMessage(promoFailed().get(0)); errorCodes = ErrorCodes.PROMO_CODE_FAILED;}
if(bookedOver!= null && bookedOver.size() > 0){setErrorMessage(bookedOver().get(0)); errorCodes = ErrorCodes.BOOKED_OVER_20; }
return errorMessage;
}
private void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ErrorCodes getErrorCodes() {
return errorCodes;
}
}
}
Please note: the root "data" object is not present in this, its handled else where via generics so I omitted it for this question
And then I would use the retrofit Error class getBodyAs method to map the incoming error to this model.
Is their a better way? Please note the backend is beyond my control.