Java使用Jackson编写Json
我目前正在为学校做一个项目,我正在尝试在json文件的末尾(在cards属性中)写一个对象,而不用使用Jackson库重写所有内容
问题是,当我尝试这样做时,我的对象被正确地写入,但它被写入文件的末尾,我尝试将它放入卡片列表中
有人有主意吗?谢谢
编辑:我已经知道如何通过重写来写入文件,为了响应老师的指示,我需要在不重写文件的情况下写入
我的Json文件:
{
"cards": [
{
"subject": "The Earth",
"questions": [
{
"challenge": "What is the highest mountain of the world?",
"answer": "Everest"
},
{
"challenge": "What is the largest ocean in the world?",
"answer": "Pacific Ocean"
}
],
"author": "Roger",
"theme": "IMPROBABLE"
},
{
"subject": "Holidays",
"questions": [
{
"challenge": "What is the most touristic country in the world?",
"answer": "France"
},
{
"challenge": "In 2019, how many pictures did vacationers take per day?",
"answer": "55"
}
],
"author": "Roger",
"theme": "PLEASURE"
}
]
}
我的班级主要:
public class Main {
public static void main(String[] args) {
Question question1 = new Question("Roger", Theme.SCHOOL, "Test", "c1", "a1");
Question question2 = new Question("Roger", Theme.SCHOOL, "Test", "c2", "a2");
BasicCard bc = new BasicCard("Roger", Theme.SCHOOL, "Test", Arrays.asList(question1,question2));
try {
File file = new File(Constants.DECK_PATH);
FileWriter fileWriter = new FileWriter(file, true);
ObjectMapper mapper = new ObjectMapper();
SequenceWriter seqWriter = mapper.writerWithDefaultPrettyPrinter().writeValues(fileWriter);
seqWriter.write(bc);
seqWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果
{
"cards": [
{
"subject": "The Earth",
"questions": [
{
"challenge": "What is the highest mountain of the world?",
"answer": "Everest"
},
{
"challenge": "What is the largest ocean in the world?",
"answer": "Pacific Ocean"
}
],
"author": "Roger",
"theme": "IMPROBABLE"
},
{
"subject": "Holidays",
"questions": [
{
"challenge": "What is the most touristic country in the world?",
"answer": "France"
},
{
"challenge": "In 2019, how many pictures did vacationers take per day?",
"answer": "55"
}
],
"author": "Roger",
"theme": "PLEASURE"
}
]
}{
"subject" : "Test",
"questions" : [ {
"challenge" : "c1",
"answer" : "a1"
}, {
"challenge" : "c2",
"answer" : "a2"
}, {
"challenge" : "c3",
"answer" : "a3"
}, {
"challenge" : "c4",
"answer" : "a4"
} ],
"author" : "Damien",
"theme" : "SCHOOL"
}
# 1 楼答案
您可以使用以下命令将json附加到现有文件中
# 2 楼答案
这里的问题是两层之间的分离:
FileWriter
提供ObjectMapper
)提供的您当前附加在较低的层(
1. The filesystem
)。该层不知道您将要编写json。它甚至不知道json是什么。它只是让您在现有文件的末尾追加更多字节您想要的是附加到现有的json结构中。为此,您必须读入现有对象,将所需对象附加到该对象,并通过将更新的对象写入文件系统来完全替换该文件