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

6tdlim6h  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(427)

我一直在尝试从java应用程序更新.json。
当使用objectmapper时,它只有一个方法,但无法计算参数。
第一个参数是要更新的对象,但我不知道如何传递它?我的意思是,它在文件中。第二个也是最后一个参数,我不知道它应该是什么。我读过文件,但仍然不知道他们想要什么。
其次,我的另一种方法是重写whole.json,但是我不能向其中写入多个人(我的json是person(people)数据库,它在每个“对象”中只有很少的字段)。再次尝试了更多的东西(例如将10个人放入列表,并将这个列表对象(示例)放入.json,但仍然只有一个人在那个里。它需要对象参数。
请帮帮我:))

z31licg0

z31licg01#

有3个主要的库来处理json
json-simple.jar
前任:

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

第二,使用gson库

new Gson().toJson(arr);

第三,使用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));

相关问题