我正在使用改造来向我的服务器发出请求。我试图为多个请求使用相同的模型,我想发送具有不同SerializedName的不同对象。 我的pojo看起来像这样:
public class BaseModel<T> implements Serializable {
@SerializedName("success")
@Expose
private boolean succcess;
@SerializedName("data")
@Expose private T data;
public boolean isSucccess() {
return succcess;
}
public void setSucccess(boolean succcess) {
this.succcess = succcess;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
如何以动态方式设置@SerializedName(“data”)?谢谢大家的时间!
代码示例:
public class BaseRequestModel<T> implements Serializable {
@SerializedName("success")
@Expose
private boolean success;
@Expose private T data;
public boolean isSucccess() {
return success;
}
public void setSucccess(boolean succcess) {
this.success = succcess;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
我发送给BaseModel的一个对象(作为T数据):
public class User implements Serializable {
transient String requestName = "user";
@SerializedName("id")
@Expose
private int id;
@SerializedName("owner_id")
@Expose private int ownerId;
@SerializedName("first_name")
@Expose private String firstName;
@SerializedName("middle_name")
@Expose private String middleName;
@SerializedName("last_name")
@Expose private String lastName;
@SerializedName("username")
@Expose private String username;
public String getRequestName() {
return requestName;
}
public void setRequestName(String requestName) {
this.requestName = requestName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
我的自定义序列化程序:
public class BaseRequestCustomSerializer<T> implements JsonSerializer<User> {
@Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
src.getRequestName();
return null;
}
}
我必须传递给序列化程序而不是特定对象,因为这就是我的问题所在。有任何想法吗?谢谢!
答案 0 :(得分:0)
如果要设置@SerializedName(&#34; data&#34;),则必须从api响应中获取相同的变量名。