Retrofit 2, same name different data type JSON Parsing

Viewed 7200

I am trying to parse a JSON response from a server, If there are changes to in the query sent in post method I will get first one as response, if not I will get the second one as response.

1:

{
    "status": 1,
    "data": {
        "firstname": "First Name",
        "lastname": "Last Name",
        "mobilenumber": "1234567894",
        "emailid": "test@gmail.com",
        "timezone": "Asia/Kolkata"
    },
    "user_id": "",
    "response": "Profile Updated Successfully"
}

2:

{
    "status": 1,
    "data": "No changes to update",
    "user_id": ""
}

As you can see if there are changes the data returns a object, if there are no changes the data returns as string.

I am using this method to get the data and I am using Gson Convertor to map the data.

This is the request interface

@FormUrlEncoded
@POST("pondguard/updateprofile")
Call<UserResponse> getInfoUpdated(@Field("user_id") String user_id,
                                  @Field("firstname") String firstName,
                                  @Field("lastname") String lastName,
                                  @Field("mobilenumber") String mobileNumber,
                                  @Field("emailid") String emailID)

and this is my POJO Class

public class UserResponse implements Parcelable {

    public static final Creator<UserResponse> CREATOR = new Creator<UserResponse>() {
        @Override
        public UserResponse createFromParcel(Parcel in) {
            return new UserResponse(in);
        }

        @Override
        public UserResponse[] newArray(int size) {
            return new UserResponse[size];
        }
    };
    private String status;
    private Data data;
    private String response;
    private String error;

    protected UserResponse(Parcel in) {
        status = in.readString();
        data = in.readParcelable(Data.class.getClassLoader());
        response = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(status);
        dest.writeParcelable(data, flags);
        dest.writeString(response);
    }

    public String getStatus() {
        return status;
    }

    public Data getData() {
        return data;
    }

    public String getResponse() {
        return response;
    }

    public String getError() {
        return error;
    }
}

and finally the Retrofit call I make:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(ConstantUtils.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

UserInfoRequestInterface requestInterface = retrofit.create(UserInfoRequestInterface.class);
Call<UserResponse> call = requestInterface.getInfoUpdated(user_id, firstName, lastName, phoneNumber, email, null, null);
3 Answers
Related