gpt4 book ai didi

android - Retrofit 2,同名不同数据类型JSON解析

转载 作者:太空宇宙 更新时间:2023-11-03 11:54:45 25 4
gpt4 key购买 nike

我正在尝试解析来自服务器的 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 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);

最佳答案

感谢您的建议,但我想出了一个可行的方法。这是我如何做到的...

首先,在我的 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);

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

关于android - Retrofit 2,同名不同数据类型JSON解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44171908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com