How to handle Json Array and Json Object same time in Retrofit Andorid

Viewed 46

I am new to Android. When the response is a success, I get a JSON Object and when it is a failure I get an empty JSON array.

I have created a POJO class for the same, but I'm getting the exception below:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 5 column 14 path $.data

When the API response is a success, I get the response below:

{
  "status": "S",
  "code": "000",
  "description": "OTP Sent Successfully",
  "data": {
    "ProcessId": "39a71-6d5c-4ae1-1415e63"
  }
}

When the response is a failure, I get the response below:

{
  "status": "F",
  "code": "002",
  "description": "Customer with Mobile already Exists",
  "data": []
}

My POJO Class:

public class SendOtpAPI {
  @SerializedName("status")
  @Expose
  private String status;
  @SerializedName("code")
  @Expose
  private String code;
  @SerializedName("description")
  @Expose
  private String description;
  @SerializedName("data")
  @Nullable
  @Expose
  private Data data;

  public String getStatus() {
    return status;
  }

  public void setStatus(String status) {
    this.status = status;
  }

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public Data getData() {
    return data;
  }

  public void setData(Data data) {
    this.data = data;
  }
}

POJO Data Class:

public class Data {
  @SerializedName("ProcessId")
  @Expose
  private String processId;

  public String getProcessId() {
    return processId;
  }

  public void setProcessId(String processId) {
    this.processId = processId;
  }
}

Retrofit API Call:

@FormUrlEncoded
@POST("https://dev2.test/otp")
Call<SendOtpAPI> sendOtpRegister(
  @Field("operation")String operation,
  @Field("mobile")String mobile
);

How can I handle this?

1 Answers

Modify your Model class- the exception itself says the solution

Check your API in Postman your response contains Array I think, And You have declared Data as an object in SendOtpAPI model class. check the below code -

Change Data class into an array in SendOtpAPI model class

private Data data; --> private ArrayList<Data> dataList;
Related