简体   繁体   English

Java - 用 Jackson 写入 Json

[英]Java - Write in a Json with Jackson

I'm currently doing a project for school and I'm trying to write an object at the end of my json file (in the cards attribute) without rewriting everything using the Jackson library.我目前正在为学校做一个项目,我正在尝试在我的 json 文件(在卡片属性中)的末尾编写一个 object,而无需使用 Jackson 库重写所有内容。

The problem is that when I try to do this my object is written correctly, but it is written at the end of the file, and I try to put it in the list of cards [ THERE ].问题是,当我尝试这样做时,我的 object 写入正确,但它写在文件末尾,我尝试将其放入卡列表 [ THERE ]。

someone have an idea?有人有想法吗? Thanks.谢谢。

EDIT: I already know how to write to a file by rewriting it, for answer to my teacher's instructions I need to do it without rewriting the file.编辑:我已经知道如何通过重写来写入文件,为了回答我老师的指示,我需要在不重写文件的情况下这样做。

My Json File:我的 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"
    }
    
  ]

}

My class Main:我的 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();
      }

  }

}

Result结果

{

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

The problem here is the separation between two layers:这里的问题是两层之间的分离:

  1. The filesystem, in your case provided through FileWriter文件系统,在您的情况下是通过FileWriter提供的
  2. The logical layer (json), in your case provided through Jackson ( ObjectMapper )逻辑层(json),在您的情况下通过 Jackson ( ObjectMapper )提供

You currently append on the lower layer ( 1. The filesystem ).您目前 append 在较低层( 1. The filesystem )。 This layer doesn't know that you're going to write json.这一层不知道你要写json。 It doesn't even know what json is.它甚至不知道 json 是什么。 It simply let's you append more bytes to the end of an existing file.它只是让你 append 更多字节到现有文件的末尾。

What you want is to append to a existing json structure.您想要的是将 append 转换为现有的 json 结构。 To do so, you have to read in the existing object, append the desired object to it and replace the file completely by writing the updated object to the filesystem.为此,您必须在现有的 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();
        }
    }

You can use the following to append the json to existing file.您可以使用以下 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