【问题标题】:How to Write Json Array to file using jackson如何使用杰克逊将 Json 数组写入文件
【发布时间】:2016-01-05 06:57:18
【问题描述】:

我创建了一个 Json 文件,我想在其中将 java 对象编写为 Array 元素。我正在使用杰克逊。

    try{
           String json;
           String phyPath = request.getSession().getServletContext().getRealPath("/");
           String filepath = phyPath + "resources/" + "data.json";
           File file = new File(filepath);
           if (!file.exists()) {
               System.out.println("pai nai");
               file.createNewFile();               
           }  
           json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(story);
           Files.write(new File(filepath).toPath(), Arrays.asList(json), StandardOpenOption.APPEND);    
    } 

这不是我真正想要的。它会创建像

这样的数据
{
  "storyTitle" : "ttt",
  "storyBody" : "tttt",
  "storyAuthor" : "tttt"
}
{
  "storyTitle" : "a",
  "storyBody" : "a",
  "storyAuthor" : "a"
}

我只需要创建一个 Json 数组,在其中添加 java 对象,数据应该是这样的

[{
  "storyTitle" : "ttt",
  "storyBody" : "tttt",
  "storyAuthor" : "tttt"
}
,{
  "storyTitle" : "a",
  "storyBody" : "a",
  "storyAuthor" : "a"
}]

【问题讨论】:

  • 无关提示:如果文件不存在,则无需创建。写信给它。
  • writeValueAsString(story); 你能显示定义story 是什么的代码吗?
  • 我得到了我写成数组的写法

标签: java json jackson


【解决方案1】:

Jackson 提供了将 JSON 数据写入 JSON 文件的内置方法。 您可以为此使用这些代码行

ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
writer.writeValue(new File("D:/cp/dataTwo.json"), jsonDataObject);
//new file(path of your file) 

jsonDataObject 是您要写入文件的实际对象(即对象或数组)。

【讨论】:

  • 我每次创建新数据时都尝试过它覆盖以前的数据。我需要将数据添加为 Json 数组的元素。
  • 知道如何使用杰克逊发布书面价值的数量吗?
【解决方案2】:

可以使用数组来完成:

    ObjectMapper objectMapper = new ObjectMapper();

    Student student = new Student();

    student.setActive(false);
    student.setFirstName("Kir");
    student.setId(123);
    student.setLastName("Ch");

    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    try {
        List<Student> listOfStudents = new ArrayList<>();
        listOfStudents.add(student);
        listOfStudents.add(student);
        objectMapper.writeValue(new File("d:/temp/output.json"), listOfStudents);
    } catch (IOException e) {
        e.printStackTrace();
    }

结果会是这样的:

[ {
  "id" : 123,
  "firstName" : "Kir",
  "lastName" : "Ch",
  "active" : false,
  "address" : null,
  "languages" : null
}, {
  "id" : 123,
  "firstName" : "Kir",
  "lastName" : "Ch",
  "active" : false,
  "address" : null,
  "languages" : null
} ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多