【问题标题】:JSON serialisation of an array when I add data添加数据时数组的 JSON 序列化
【发布时间】:2018-07-20 16:41:18
【问题描述】:

我有一个表单,允许我输入有关单个项目的数据。每次有人提交一个 Item 时,我都想将它添加到一个 JSON 数组中,该数组存储在一个文件中。

这是我的代码:

for (Item obj : list) {

    out.print(obj.getId());
    out.println("");
    out.print(obj.getProductName());
    out.println("");
    out.print(obj.getPrice());
    out.println("");
    out.print(obj.getType());
    out.println("");

}

ObjectMapper mapper = new ObjectMapper();
File file=new File("D:\\extern_2\\src\\java\\JSON\\jsonlist.json");
if (!file.exists()) {
    file.createNewFile();
}



PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writerWithDefaultPrettyPrinter().writeValue(print, list);

问题是每次我添加一个新项目时,都会创建一个新的 JSON 数组并将其附加到现有文件内容中。

期望的输出:

[ {
  "id" : 56,
  "productname" : "kklll",
  "price" : "56",
  "type" : "Hot Coffee",
  "productName" : "kklll"
    } , {
  "id" : 89,
  "productname" : "llll",
  "price" : "43",
  "type" : "Drinks",
  "productName" : "llll"
} ]

实际输出:

[ {
"id" : 56,
"productname" : "kklll",
"price" : "56",
"type" : "Hot Coffee",
"productName" : "kklll"
  } ][ {
"id" : 89,
"productname" : "llll",
"price" : "43",
"type" : "Drinks",
"productName" : "llll"
} ]

为什么它会追加一个新数组而不是将我的新项目添加到现有数组中?

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    查看您正在创建的FileWriternew FileWriter(file, true)That second parameter tells the FileWriter to simply append information to the end of the file. 如果您正在修改现有的 JSON,则每次都需要覆盖该文件。这意味着第一次创建Item 时,ObjectMapper 会将其写为有效的 JSON 字符串,表示具有单个对象的数组。第二次创建Item 时,它会为您的新对象做同样的事情,创建一个只有一个对象的数组(第二个Item)并将其写入文件,即使该文件已经包含一个数组.在任何时候,您都不会真正查看文件以查看它是否包含任何现有数据。您也没有将文件解析为 JSON,这将允许您获取 现有 JSON 数组并向其中添加一些内容。

    你的流程应该是这样的:

    1. 使用ObjectMapper 读入文件中的现有数据。由于您的文件包含 Item 对象数组,因此在您读入文件后,您应该以 List<Item> 结束
    2. 将您的新Item 添加到List
    3. 将您的List<Item> 转换为 JSON 并将其写入您的 .json 文件。确保覆盖您的 .json 文件,而不仅仅是附加到它。

    【讨论】:

    • 如果你能帮助我,我无法为此编写代码。
    猜你喜欢
    • 2013-04-06
    • 2016-10-16
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2013-10-08
    • 2015-10-18
    相关资源
    最近更新 更多