簡體   English   中英

Java - 用 Jackson 寫入 Json

[英]Java - Write in a Json with Jackson

我目前正在為學校做一個項目,我正在嘗試在我的 json 文件(在卡片屬性中)的末尾編寫一個 object,而無需使用 Jackson 庫重寫所有內容。

問題是,當我嘗試這樣做時,我的 object 寫入正確,但它寫在文件末尾,我嘗試將其放入卡列表 [ 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"
    }
    
  ]

}

我的 class 主要:

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. 文件系統,在您的情況下是通過FileWriter提供的
  2. 邏輯層(json),在您的情況下通過 Jackson ( ObjectMapper )提供

您目前 append 在較低層( 1. The filesystem )。 這一層不知道你要寫json。 它甚至不知道 json 是什么。 它只是讓你 append 更多字節到現有文件的末尾。

您想要的是將 append 轉換為現有的 json 結構。 為此,您必須在現有的 object、append 中讀取所需的 object,並通過將更新的 ZA8CFDE63931CCFEB6666662ACZ931CCFEB6666662ACZ88 寫入文件系統來完全替換文件。

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

您可以使用以下 append 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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM