【发布时间】:2018-07-20 16:41:18
【问题描述】:
我有一个表单,允许我输入有关单个项目的数据。每次有人提交一个 Item 时,我都想将它添加到一个 JSON 数组中,该数组存储在一个文件中。
这是我的代码:
for (Item obj : list) {
out.print(obj.getId());
out.println("");
out.print(obj.getProductName());
out.println("");
out.print(obj.getPrice());
out.println("");
out.print(obj.getType());
out.println("");
}
ObjectMapper mapper = new ObjectMapper();
File file=new File("D:\\extern_2\\src\\java\\JSON\\jsonlist.json");
if (!file.exists()) {
file.createNewFile();
}
PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writerWithDefaultPrettyPrinter().writeValue(print, list);
问题是每次我添加一个新项目时,都会创建一个新的 JSON 数组并将其附加到现有文件内容中。
期望的输出:
[ {
"id" : 56,
"productname" : "kklll",
"price" : "56",
"type" : "Hot Coffee",
"productName" : "kklll"
} , {
"id" : 89,
"productname" : "llll",
"price" : "43",
"type" : "Drinks",
"productName" : "llll"
} ]
实际输出:
[ {
"id" : 56,
"productname" : "kklll",
"price" : "56",
"type" : "Hot Coffee",
"productName" : "kklll"
} ][ {
"id" : 89,
"productname" : "llll",
"price" : "43",
"type" : "Drinks",
"productName" : "llll"
} ]
为什么它会追加一个新数组而不是将我的新项目添加到现有数组中?
【问题讨论】:
标签: java json serialization jackson