一尘不染

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

json

我正在尝试从服务器解析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 Converter来映射数据。

这是请求界面

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

阅读 229

收藏
2020-07-27

共1个答案

一尘不染

谢谢您的建议,但我想出了一种可行的方法。这是我的方法…

首先,在我的Pojo课堂上,我添加了一个JsonDeserializer,然后检查“数据”是对象还是基元,并据此设置相应的字段。

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

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

2020-07-27