我创建了一个 Json 文件,我想在其中编写 java 对象作为 Array 元素。我正在使用 jackson 。
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"
}]
最佳答案
Jackson 提供了将 JSON 数据写入 JSON 文件的内置方法。 你可以为此使用这些代码行
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
writer.writeValue(new File("D:/cp/dataTwo.json"), jsonDataObject);
//new file(path of your file)
和 jsonDataObject
是您要写入文件的实际对象(即对象或数组)。
关于java - 如何使用 jackson 将 Json 数组写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34605832/