【发布时间】:2015-06-10 05:19:55
【问题描述】:
我有五个班级:
Comment,Paper,WoundPaper,Document,WoundDoc.
Comment 是文本的持有者。Paper 是空的抽象类。WoundPaper 扩展Paper 并存储Comments 的String 和ArrayList。
@ 987654331@是抽象类,存储<? 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 将其转换为 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 到 JSON >> {"paperList":[{},{}]}
正如我之前显示的,WoundDoc 存储WoundPaper 的列表,每个WoundPaper 存储comments 的列表。但是为什么输出中没有comment?
【问题讨论】:
-
我通常在没有第三方库的情况下自己创建 json。只是因为 json 不需要任何标题。
-
既然有文档齐全、经过测试和广泛部署的库可以为您完成,为什么还要为您需要序列化的每个对象编写自定义序列化程序?
-
@beresfordt 这似乎是个不错的方法,对我来说可能更好。我会试试的。谢谢!
标签: java json generics arraylist gson