首页 > 解决方案 > Java - 与 Jackson 一起编写 Json

问题描述

我目前正在为学校做一个项目,我正在尝试在我的 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"
}

标签: javajsonjacksonoverwritewrite

解决方案


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

  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();
        }
    }

推荐阅读