Skip to content Skip to sidebar Skip to footer

Retrofit 2, Same Name Different Data Type Json Parsing

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 r

Solution 1:

Thank you for your suggestions, but I figured out a working method. Here is how I did it...

First, in my Pojo class, I added a JsonDeserializer, then I check if the "data" is an object or primitive and depending on that I set the respective fields.

publicclassUserResponse  {

    @SerializedName("status")
    privateString status;
    @SerializedName("data")
    privateObject mData;
    @SerializedName("response")
    privateString response;
    @SerializedName("error")
    privateString error;

    privateString message;
    privateString firstname;
    privateString lastname;
    privateString mobilenumber;
    privateString emailid;
    privateString timezone;

    publicStringgetMessage() {
        return message;
    }

    publicvoidsetMessage(String message) {
        this.message = message;
    }

    publicStringgetFirstname() {
        return firstname;
    }

    publicvoidsetFirstname(String firstname) {
        this.firstname = firstname;
    }

    publicStringgetLastname() {
        return lastname;
    }

    publicvoidsetLastname(String lastname) {
        this.lastname = lastname;
    }

    publicStringgetMobilenumber() {
        return mobilenumber;
    }

    publicvoidsetMobilenumber(String mobilenumber) {
        this.mobilenumber = mobilenumber;
    }

    publicStringgetEmailid() {
        return emailid;
    }

    publicvoidsetEmailid(String emailid) {
        this.emailid = emailid;
    }

    publicStringgetTimezone() {
        return timezone;
    }

    publicvoidsetTimezone(String timezone) {
        this.timezone = timezone;
    }

    publicStringgetStatus() {
        return status;
    }

    publicvoidsetStatus(String status) {
        this.status = status;
    }

    publicObjectgetmData() {
        return mData;
    }

    publicStringgetResponse() {
        return response;
    }

    publicStringgetError() {
        return error;
    }

    publicstaticclassDataStateDeserializerimplementsJsonDeserializer<UserResponse> {

        @OverridepublicUserResponsedeserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            UserResponse userResponse = newGson().fromJson(json, UserResponse.class);
            JsonObject jsonObject = json.getAsJsonObject();

            if (jsonObject.has("data")) {
                JsonElement elem = jsonObject.get("data");
                if (elem != null && !elem.isJsonNull()) {                     
                    if(elem.isJsonPrimitive()){                            
                        userResponse.setMessage(elem.getAsString());
                    }else{

                        userResponse.setFirstname(elem.getAsJsonObject().get("firstname").getAsString());
                        userResponse.setLastname(elem.getAsJsonObject().get("lastname").getAsString());
                        userResponse.setMobilenumber(elem.getAsJsonObject().get("mobilenumber").getAsString());
                        userResponse.setEmailid(elem.getAsJsonObject().get("emailid").getAsString());
                        userResponse.setTimezone(elem.getAsJsonObject().get("timezone").getAsString());
                    }
                }
            }
            return userResponse ;
        }
    }
}

and I attach the json deserializer to the type adapter of GSON Builder and give it to create method of GsonConvertor in Retrofit like this

Gsongson=newGsonBuilder()
                 .registerTypeAdapter(UserResponse.class, newUserResponse.DataStateDeserializer())
                .create();

Retrofitretrofit=newRetrofit.Builder()
                .baseUrl(ConstantUtils.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

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

Then all I have to do is check if message is null or not and perform my required action accordingly.

Solution 2:

You cannot use like that. You have a status field in the response. Use the status filed to check for any data present. for example :

if the status is 1:

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

and if the status is 0 :

{"status":0,"data":{"firstname":"","lastname":"","mobilenumber":"","emailid":"","timezone":""},"user_id":"","response":"An error message"}

Solution 3:

try this,

try {
        // "data" returns an objectJSONObject jsonObjectData = jsonObject.getJSONObject("data");
        //rest of your code
    } catch (JSONException e){
        //"data" returns a string
        e.printStackTrace();
        try {
            String data = jsonObject.getString("data");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    }

Post a Comment for "Retrofit 2, Same Name Different Data Type Json Parsing"