简体   繁体   English

更新 json 文件/从 java 将多个值写入 json

[英]updating json file / writing more than one value into json from java

im stuck at trying to update .json from java app.我一直在尝试从 Java 应用程序更新 .json。

theres only one method from it when using ObjectMapper but cant figure out parameters.使用 ObjectMapper 时只有一种方法,但无法找出参数。

first parameter is object to update but i have no idea how to pass it?第一个参数是要更新的对象,但我不知道如何传递它? i mean, its in file.我的意思是,它在文件中。 second and last parameter i have no idea what it is supposed to be.第二个也是最后一个参数我不知道它应该是什么。 ive read docs but still- no idea what they want there.我阅读了文档,但仍然不知道他们想要什么。

secondly, my other approach was to just rewrite whole .json but then i couldnt write more than one person into it (my json is Person (people) database - it has few fields within each "object").其次,我的另一种方法是重写整个 .json,但随后我不能将多个人写入其中(我的 json 是 Person(人)数据库 - 每个“对象”中的字段很少)。 again tried more stuff (eg putting 10 people into List and putting this list object (instance) into .json but still only one person is there. it requires Object parameter.再次尝试了更多的东西(例如,将 10 个人放入 List 并将此列表对象(实例)放入 .json 但仍然只有一个人在那里。它需要 Object 参数。

please help me :)))请帮我 :)))

There are 3 main libraries to deal with json有 3 个主要的库来处理 json

  1. json-simple.jar json-simple.jar

ex:前任:

List arr = new ArrayList();  
arr.add("sonoo");    
arr.add(new Integer(27));    
arr.add(new Double(600000));   
String jsonText = JSONValue.toJSONString(arr);  

2nd by using gson library 2nd 使用 gson 库

new Gson().toJson(arr);

3rd by using jackson第三次使用杰克逊

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM