【发布时间】:2016-01-05 06:57:18
【问题描述】:
我创建了一个 Json 文件,我想在其中将 java 对象编写为 Array 元素。我正在使用杰克逊。
try{
String json;
String phyPath = request.getSession().getServletContext().getRealPath("/");
String filepath = phyPath + "resources/" + "data.json";
File file = new File(filepath);
if (!file.exists()) {
System.out.println("pai nai");
file.createNewFile();
}
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(story);
Files.write(new File(filepath).toPath(), Arrays.asList(json), StandardOpenOption.APPEND);
}
这不是我真正想要的。它会创建像
这样的数据{
"storyTitle" : "ttt",
"storyBody" : "tttt",
"storyAuthor" : "tttt"
}
{
"storyTitle" : "a",
"storyBody" : "a",
"storyAuthor" : "a"
}
我只需要创建一个 Json 数组,在其中添加 java 对象,数据应该是这样的
[{
"storyTitle" : "ttt",
"storyBody" : "tttt",
"storyAuthor" : "tttt"
}
,{
"storyTitle" : "a",
"storyBody" : "a",
"storyAuthor" : "a"
}]
【问题讨论】:
-
无关提示:如果文件不存在,则无需创建。写信给它。
-
writeValueAsString(story);你能显示定义story是什么的代码吗? -
我得到了我写成数组的写法