[英]updating json file / writing more than one value into json from java
我一直在尝试从 Java 应用程序更新 .json。
使用 ObjectMapper 时只有一种方法,但无法找出参数。
第一个参数是要更新的对象,但我不知道如何传递它? 我的意思是,它在文件中。 第二个也是最后一个参数我不知道它应该是什么。 我阅读了文档,但仍然不知道他们想要什么。
其次,我的另一种方法是重写整个 .json,但随后我不能将多个人写入其中(我的 json 是 Person(人)数据库 - 每个“对象”中的字段很少)。 再次尝试了更多的东西(例如,将 10 个人放入 List 并将此列表对象(实例)放入 .json 但仍然只有一个人在那里。它需要 Object 参数。
请帮我 :)))
有 3 个主要的库来处理 json
前任:
List arr = new ArrayList();
arr.add("sonoo");
arr.add(new Integer(27));
arr.add(new Double(600000));
String jsonText = JSONValue.toJSONString(arr);
2nd 使用 gson 库
new Gson().toJson(arr);
第三次使用杰克逊
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode();
/**
* Create three JSON Objects objectNode1, objectNode2, objectNode3
* Add all these three objects in the array
*/
ObjectNode objectNode1 = mapper.createObjectNode();
objectNode1.put("bookName", "Java");
objectNode1.put("price", "100");
ObjectNode objectNode2 = mapper.createObjectNode();
objectNode2.put("bookName", "Spring");
objectNode2.put("price", "200");
ObjectNode objectNode3 = mapper.createObjectNode();
objectNode3.put("bookName", "Liferay");
objectNode3.put("price", "500");
/**
* Array contains JSON Objects
*/
arrayNode.add(objectNode1);
arrayNode.add(objectNode2);
arrayNode.add(objectNode3);
/**
* We can directly write the JSON in the console.
* But it wont be pretty JSON String
*/
System.out.println(arrayNode.toString());
/**
* To make the JSON String pretty use the below code
*/
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.