将数据附加到json文件

问题描述 投票:0回答:1

当我调用

writeToJsonFile
function 方法时,它会正确写入文件,但是当我调用
UpdateJSONFileData
时,它不会将数据附加到文件中进行覆盖。

这里的目标是通过直接传递键和值或传递对象将数据写入文件

public static void writeTojsonFile(String key, 
                                   String value, 
                                   String fileName, 
                                   Object object)
{
JSONObject jsonObject = new JSONObject();
ObjectMapper objectMapper= new ObjectMapper();
try{
  FileWriter file = new FileWriter(filePath);
  if(object == null)
  {
     jsonObject.put(key, value);
     file.write(jsonObject.toJSONString());
     file.flush();
   }
 else
 {
     objectMapper.writeValue(new File(fileName), object);
  }
}catch (IOException e) {
e.printStackTrace();
}}

public static void UpdateJSONFileData(String Key, 
                                      String value, 
                                      String filePath, 
                                      Object object) throws
                                           FileNotFoundException, 
                                           IOException, 
                                           ParseException {

ObjectMapper objectMapper = new ObjectMapper()
ObjectNode objectNode = new ObjectNode(null);
objectNode = objectMapper.readValue(new File(filePath), objectNode.getClass());
if(object == null)
   {
       objectNode.put(key, value);
       objectMapper.writeValue(new File(filePath), objectNode);
   }
else{
       objectMapper.writeValue(new File(filePath), object);
    }
}

目前我将 function 方法调用为

writeTojsonFile("Role", "Engineer", "/src/employeeInfo.json", null)

JSONObject empInfo = new JSONObject();
empInfo.put("ID","1234");
empInfo.put("Name","John")

UpdateJSONFileData("","", "/src/employeeInfo.json", empInfo)

所需输出为:

{"Role":"Engineer","ID":"1234", "Name":"John"}

但其覆盖为

{"ID":"1234", "Name":"John"}
java json writetofile
1个回答
0
投票

虽然下面将附加对象,但我不确定为什么要将两个独立的 JSON 对象写入文件。也许您正在编写一个每行一个 json 文件。

//The if block rewrites the file, there is no problem here
if(object == null)
   {
       objectNode.put(key, value);
       objectMapper.writeValue(new File(filePath), objectNode);
   }
//The else block also rewrites the file as well. Reason is when the
//OutputStream is opened by Jackson, it is not in append mode
//Try opening the file stream in append mode 
//FileOutputStream(File file,boolean append)
//and use ObjectMapper.writeValue(OutputStream out,Object value)
//flush and close the stream
//That should address the issue, give it a try
else{
       objectMapper.writeValue(new File(filePath), object);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.