【发布时间】:2023-03-08 02:31:01
【问题描述】:
我目前正在为学校做一个项目,我正在尝试在我的 json 文件末尾(在卡片属性中)编写一个对象,而无需使用 Jackson 库重写所有内容。
问题是,当我尝试执行此操作时,我的对象写入正确,但它写在文件末尾,我尝试将其放入卡片列表 [ THERE ]。
有人有想法吗?谢谢。
编辑:我已经知道如何通过重写来写入文件,为了回答我老师的指示,我需要在不重写文件的情况下这样做。
我的 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"
}
【问题讨论】:
-
您可以创建一个新类来表示 json 的字段。然后,您可以读取 json 文件并使用 objectMapper 将 json 转换为您的对象。在此之后,您可以将卡片添加到列表中并再次使用 objectMapper 将您的对象序列化为 json。
-
但是文件是这样重写的。我想插入我的元素。
标签: java json jackson overwrite write