【发布时间】:2015-03-01 13:29:24
【问题描述】:
我有一个不同的数据类型,它作为我通过改造获取的 json。这是消息类型为图像时的外观
{
"_id": ObjectId("54cd78c79ce8756749a8e38c"),
"data": {
"image_name": "10347646_865379743494769_4408387832275449094_n.png",
"image_url": "https://s3-ap-southeast-1.amazonaws.com/clan/e492006e561fe3811e3e16c85d384cf6.png",
"image_size": 76586
},
"receiver_id": "54cd2fb7847828d73ce9047d",
"sender_id": ObjectId("54cd4354bb8c1b2540bad504"),
"server_recieved_at": ISODate("2015-02-01T00:52:23.676Z"),
"sent_at": ISODate("2015-02-01T00:52:23.676Z"),
"created_at": ISODate("2015-02-01T00:52:23.676Z"),
"needs_push": true,
"type": "image",
"status": "sent",
"__v": 0
}
消息类型可以不同,可以是视频、图像或文本。对于视频,数据如下所示:
"data": {
"video_name": "aa_n.mp4",
"video_url": "https://s3-ap-southeast-1.amazonaws.com/clan/aa_n.png",
"video_size": 76586
},
在 json 中指定了一个消息类型,它告诉存在什么类型的数据。
如何在 GSON 中反序列化这些数据。我为视频和图像创建了一个通用的 MessageData 类和类。但我无法理解用 gson 设置数据。
更新问题。这是我的消息类。
@Parcel
public class Message {
@SerializedName("sender_id")
private String senderId;
@SerializedName("receiver_id")
private String receiverId;
@SerializedName("status")
private String status;
@SerializedName("type")
private String type;
@SerializedName("read_status")
private boolean readStatus;
@SerializedName("text")
private String text;
@SerializedName("needs_push")
private boolean needsPush;
//TODO Need to set the data variable
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getReceiverId() {
return receiverId;
}
public void setReceiverId(String receiverId) {
this.receiverId = receiverId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isReadStatus() {
return readStatus;
}
public void setReadStatus(boolean readStatus) {
this.readStatus = readStatus;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean isNeedsPush() {
return needsPush;
}
public void setNeedsPush(boolean needsPush) {
this.needsPush = needsPush;
}
我已经创建了图像和视频类。
@Parcel
public class Image {
@SerializedName("image_size")
private Double imageSize;
@SerializedName("image_url")
private String imageUrl;
@SerializedName("image_name")
private String imageName;
}
根据 json 对象,消息数据对象会有所不同,可以是图像或视频。如何根据类型将其序列化为 gson 对象。
【问题讨论】:
标签: java android json gson retrofit