我有五類:爲什麼谷歌Gson.toJson丟失數據
Comment
,Paper
,WoundPaper
,Document
,WoundDoc
。
Comment
是文本的持有者。
Paper
是空的和抽象類。
WoundPaper
延伸Paper
並存儲一個String和一個ArrayList Comments
。
Document
是抽象類,存儲<? extends Paper>
的ArrayList。
WoundDoc
延伸Document
。
你可以看到下面這些類:
評論類:
public class Comment {
private final String text;
public static class Builder {
private final String text;
public Builder(String text) {
this.text = text;
}
public Comment build(){
return new Comment(this);
}
}
private Comment(Builder builder) {
this.text = builder.text;
}
public String getText() {
return text;
}
}
紙張類:
public abstract class Paper {
protected Paper(ArrayList<Comment> commentList) {
}
}
WoundPaper類:
public class WoundPaper extends Paper {
private final String imageUri;
private final ArrayList<Comment> commentList;
public static class Builder {
private final String imageUri;
private final ArrayList<Comment> commentList;
public Builder(String imageUri, ArrayList<Comment> commentList) {
this.imageUri = imageUri;
this.commentList = commentList;
}
public WoundPaper build() {
return new WoundPaper(this);
}
}
private WoundPaper(Builder builder) {
super(builder.commentList);
this.imageUri = builder.imageUri;
this.commentList = builder.commentList;
}
}
文檔類:
public abstract class Document {
private final ArrayList<? extends Paper> paperList;
protected Document(ArrayList<? extends Paper> paperList) {
this.paperList = paperList;
}
}
WoundDoc類:
public class WoundDoc extends Document {
public static class Builder {
private final ArrayList<WoundPaper> paperList;
public Builder(ArrayList<WoundPaper> paperList) {
this.paperList = paperList;
}
public WoundDoc build() {
return new WoundDoc(this);
}
}
private WoundDoc(Builder builder) {
super(builder.paperList);
}
}
現在我要創建的WoundDoc
的實例並將其轉換成由Gson.This JSON字符串是一個示例代碼來做到這一點:
Comment comment = new Comment.Builder("comment").build();
ArrayList<Comment> commentList = new ArrayList<Comment>();
commentList.add(comment);
commentList.add(comment);
WoundPaper woundPaper = new WoundPaper.Builder("some Uri", commentList).build();
ArrayList<WoundPaper> woundPaperList = new ArrayList<WoundPaper>();
woundPaperList.add(woundPaper);
woundPaperList.add(woundPaper);
WoundDoc woundDoc = new WoundDoc.Builder(woundPaperList).build();
System.out.println("woundDoc to JSON >> " + gson.toJson(woundDoc));
但輸出很奇怪:
woundDoc to JSON> > { 「paperList」:[{},{}]}
正如我之前顯示,WoundDoc
商店WoundPaper
列表以及每個WoundPaper
存儲comment
s.But的列表爲什麼在輸出沒有comment
?
我通常在沒有第三方庫的情況下自己創建我的json。僅僅因爲json不需要任何頭文件。 – 2015-04-05 18:35:44
爲什麼要爲您需要序列化的每個對象編寫自定義序列化程序,而這些對象是有文檔記錄的,經過測試的和廣泛部署的庫,可以爲您做到這一點? – beresfordt 2015-04-05 19:47:42
@beresfordt這似乎是一個很好的方法,對我來說可能更好,我會試試。謝謝! – hasanghaforian 2015-04-05 20:31:18