改造2,同名不同的数据类型JSON解析

时间:2017-05-25 03:42:04

标签: android json retrofit2

我正在尝试解析来自服务器的JSON响应,如果在post方法中发送的查询中有更改,我将获得第一个作为响应,如果不是,我将获得第二个作为响应。

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": ""
}

正如您所看到的,如果有更改,data会返回一个对象,如果没有更改,data将返回为字符串。

我正在使用此方法获取数据,而我正在使用Gson Convertor来映射数据。

这是请求界面

@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)

这是我的POJO班级

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;
    }
}

最后我做了一次改装电话:

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 个答案:

答案 0 :(得分:7)

感谢您的建议,但我找到了一种有效的方法。我是这样做的......

首先,在我的Pojo课程中,我添加了一个JsonDeserializer,然后检查&#34;数据&#34;是一个对象或原语,并根据我设置相应的字段。

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 ;
        }
    }
}

我将json反序列化器附加到GSON Builder的类型适配器,并让它在Retrofit中创建GsonConvertor的方法,就像这样

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);

然后,我所要做的就是检查消息是否为空,并相应地执行我所需的操作。

答案 1 :(得分:0)

你不能那样用。您在回复中有一个status字段。使用status字段检查是否存在任何数据。例如:

如果状态为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"
}

如果status为0:

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

答案 2 :(得分:0)

试试这个,

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();
        }
    }