有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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"
}

共 (2) 个答案

  1. # 1 楼答案

    您可以使用以下命令将json附加到现有文件中

    void write() {
        ObjectMapper om = new ObjectMapper()
        ObjectNode original = om.readValue(new File("oldFile.json"), ObjectNode)
    
        Subject s = new Subject(List.of(new Question("c1", "a1"),
                                 new Question("c2", "a2")), "Test")
    
        original.set("questions", om.valueToTree(s))
    
        om.writeValue(new File("newFile.json"), original)
    }
    
  2. # 2 楼答案

    这里的问题是两层之间的分离:

    1. 文件系统,在您的例子中,通过FileWriter提供
    2. 逻辑层(json),在您的例子中是通过Jackson(ObjectMapper)提供的

    您当前附加在较低的层(1. The filesystem)。该层不知道您将要编写json。它甚至不知道json是什么。它只是让您在现有文件的末尾追加更多字节

    您想要的是附加到现有的json结构中。为此,您必须读入现有对象,将所需对象附加到该对象,并通过将更新的对象写入文件系统来完全替换该文件

        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));
            
            ObjectMapper mapper = new ObjectMapper();
            File file = new File(Constants.DECK_PATH);
    
            try {
                // read the existing object from the file
                Map<String, List<BasicCard>> object = mapper.readValue(file, new TypeReference<Map<String, List<BasicCard>>>(){});
                // append your BasicCard bc to the list
                object.computeIfAbsent("cards", k -> new ArrayList<>()).add(bc);
                
                // override the contents of the file by writing the object entirely again
                mapper.writeValue(file, object);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }