Retrofit 2, same name different data type JSON Parsing

后端 未结 3 1422
时光取名叫无心
时光取名叫无心 2020-12-03 19:40

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 o

相关标签:
3条回答
  • 2020-12-03 19:51

    try this,

    try {
            // "data" returns an object
            JSONObject 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();
            }
        }
    
    0 讨论(0)
  • 2020-12-03 20:00

    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.

    public class UserResponse  {
    
        @SerializedName("status")
        private String status;
        @SerializedName("data")
        private Object mData;
        @SerializedName("response")
        private String response;
        @SerializedName("error")
        private String error;
    
        private String message;
        private String firstname;
        private String lastname;
        private String mobilenumber;
        private String emailid;
        private String timezone;
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public String getFirstname() {
            return firstname;
        }
    
        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }
    
        public String getLastname() {
            return lastname;
        }
    
        public void setLastname(String lastname) {
            this.lastname = lastname;
        }
    
        public String getMobilenumber() {
            return mobilenumber;
        }
    
        public void setMobilenumber(String mobilenumber) {
            this.mobilenumber = mobilenumber;
        }
    
        public String getEmailid() {
            return emailid;
        }
    
        public void setEmailid(String emailid) {
            this.emailid = emailid;
        }
    
        public String getTimezone() {
            return timezone;
        }
    
        public void setTimezone(String timezone) {
            this.timezone = timezone;
        }
    
        public String getStatus() {
            return status;
        }
    
        public void setStatus(String status) {
            this.status = status;
        }
    
        public Object getmData() {
            return mData;
        }
    
        public String getResponse() {
            return response;
        }
    
        public String getError() {
            return error;
        }
    
        public static class DataStateDeserializer implements JsonDeserializer<UserResponse> {
    
            @Override
            public UserResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                UserResponse userResponse = new Gson().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

    Gson gson = new GsonBuilder()
                     .registerTypeAdapter(UserResponse.class, new UserResponse.DataStateDeserializer())
                    .create();
    
    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ConstantUtils.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
    
    UserInfoRequestInterface requestInterface = 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.

    0 讨论(0)
  • 2020-12-03 20:09

    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"
    }
    
    0 讨论(0)
提交回复
热议问题