我的 Api 响应如下所示。
{
"status" : 1,
"message" : "Some Message",
"data" : {
}
}
我的响应类如下所示。数据类型根据发出的请求而变化。
public class Response<T>{
@Expose
@SerializedName("status")
private Integer status;
@Expose
@SerializedName("message")
private String message;
@Expose
@SerializedName("data")
private T data;
//Getters and Setters
}
问题1.如何使用gson解析这个json?
Response<ClassA> response = new Gson().fromJson(jsonString, ??);
问题 2.我如何为此类编写 Parcelable 实现。
dest.writeInt(status == null ? 0:status);
dest.writeString(message);
??
最佳答案
您需要对模型结构进行一些更改。为此..
创建一个 BaseDTO,它只不过是您的 Response 类,并使用 ClassA 扩展您的 BaseDTO。
BaseDto.class
public class BaseDto {
@Expose
@SerializedName("status")
protected Integer status;
@Expose
@SerializedName("message")
protected String message;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
A类.class
public class ClassA extends BaseDto implements Parcelable {
String name;
protected ClassA(Parcel in) {
name = in.readString();
status = in.readByte() == 0x00 ? null : in.readInt();
message = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
if (status == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(status);
}
dest.writeString(message);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<ClassA> CREATOR = new Parcelable.Creator<ClassA>() {
@Override
public ClassA createFromParcel(Parcel in) {
return new ClassA(in);
}
@Override
public ClassA[] newArray(int size) {
return new ClassA[size];
}
};
}
使用此站点生成 Parcelable 类 http://www.parcelabler.com/
要使用 gson 进行解析,您只需将其类型传递给它..
我写了一个函数来简化这个.. 将它们保存在 Util 类中
public static <T> String convertObjectToStringJson(T someObject, Type type) {
Gson gson = new Gson();
String strJson = gson.toJson(someObject, type);
return strJson;
}
public static <T> T getObjectFromJson(String json, Type type) {
Gson gson = new Gson();
if (json != null) {
if (json.isEmpty()) {
return null;
}
}
return gson.fromJson(json, type);
}
使用这些函数的示例:
ClassA classA = Util.getObjectFromJson(strJson, new TypeToken<ClassA>() {}.getType());
String jsonClassA = Util.convertObjectToStringJson(objClassA, new TypeToken<ClassA>() {}.getType());
关于java - 使用gson将json转换为包含模板变量的类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891517/