我正在尝试一个简单的测试,其中的代码会添加一些json条目,但是每次都会被覆盖(json文件在运行后将只有1个条目)。 我知道我需要以某种方式使用'[]'在JSON中创建一个数组,但是我该怎么做呢? 另外,还有更好的方法吗? 我一直在搜索,每个库似乎都有大量用户编写的代码,很笨拙。 谢谢

public class REEEE {  private static Staff createStaff() {      Staff staff = new Staff();      staff.setName("mkyong");     staff.setAge(38);     staff.setPosition(new String[] { "Founder", "CTO", "Writer" });     Map<String, Double> salary = new HashMap() {         {             put("2010", 10000.69);         }     };     staff.setSalary(salary);     staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));      return staff; }  public static void main(String[] args) throws IOException {     ObjectMapper mapper = new ObjectMapper();      File file = new File("src//j.json");             for(int i = 0; i < 4; i++) {         Staff staff = createStaff();          try {             // Java objects to JSON file             mapper.writeValue(file, staff);              // Java objects to JSON string - compact-print             String jsonString = mapper.writeValueAsString(staff);          } catch (IOException e) {             e.printStackTrace();         }     }     } } 

===============>>#1 票数:2

您可以在“列表”中添加人员,然后将列表写入文件,如下所示:

List<Staff> staffList = new LinkedList<>() for(int i = 0; i < 4; i++) {     Staff staff = createStaff();     staffList.add(staff); } mapper.writeValue(file, staffList); 

希望能帮助到你。

  ask by reeeeeeeeeeee translate from so

===============>>#2 票数:0

Jackson实现是解析和生成JSON负载。 所有与添加新元素到数组并写回文件有关的逻辑都需要自己实现。 要做起来不难:

class JsonFileAppender {     private final ObjectMapper jsonMapper;      public JsonFileAppender() {         this.jsonMapper = JsonMapper.builder().build();     }      public void appendToArray(File jsonFile, Object value) throws IOException {         Objects.requireNonNull(jsonFile);         Objects.requireNonNull(value);         if (jsonFile.isDirectory()) {             throw new IllegalArgumentException("File can not be a directory!");         }          JsonNode node = readArrayOrCreateNew(jsonFile);         if (node.isArray()) {             ArrayNode array = (ArrayNode) node;             array.addPOJO(value);         } else {             ArrayNode rootArray = jsonMapper.createArrayNode();             rootArray.add(node);             rootArray.addPOJO(value);             node = rootArray;         }         jsonMapper.writeValue(jsonFile, node);     }      private JsonNode readArrayOrCreateNew(File jsonFile) throws IOException {         if (jsonFile.exists() && jsonFile.length() > 0) {             return jsonMapper.readTree(jsonFile);         }          return jsonMapper.createArrayNode();     } } 

某些用例的用法示例:

import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.databind.node.ArrayNode;  import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects;  public class JsonPathApp {      public static void main(String[] args) throws Exception {         Path jsonTmpFile = Files.createTempFile("json", "array");         JsonFileAppender jfa = new JsonFileAppender();          // Add POJO         jfa.appendToArray(jsonTmpFile.toFile(), createStaff());         printContent(jsonTmpFile); //1          // Add primitive         jfa.appendToArray(jsonTmpFile.toFile(), "Jackson");         printContent(jsonTmpFile); //2          // Add another array         jfa.appendToArray(jsonTmpFile.toFile(), Arrays.asList("Version: ", 2, 10, 0));         printContent(jsonTmpFile); //3          // Add another object         jfa.appendToArray(jsonTmpFile.toFile(), Collections.singletonMap("simple", "object"));         printContent(jsonTmpFile); //4     }      private static Staff createStaff() {         Staff staff = new Staff();          staff.setName("mkyong");         staff.setAge(38);         staff.setPosition(new String[]{"Founder", "CTO", "Writer"});         Map<String, Double> salary = new HashMap<>();         salary.put("2010", 10000.69);          staff.setSalary(salary);         staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));          return staff;     }      private static void printContent(Path path) throws IOException {         List<String> lines = Files.readAllLines(path);         System.out.println(String.join("", lines));     } } 

上面的代码显示4行:
1个

[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]}] 

2

[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson"] 

3

[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0]] 

4

[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0],{"simple":"object"}] 

  ask by reeeeeeeeeeee translate from so

本文未有回复,本站智能推荐: