簡體   English   中英

更新 json 文件/從 java 將多個值寫入 json

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

我一直在嘗試從 Java 應用程序更新 .json。

使用 ObjectMapper 時只有一種方法,但無法找出參數。

第一個參數是要更新的對象,但我不知道如何傳遞它? 我的意思是,它在文件中。 第二個也是最后一個參數我不知道它應該是什么。 我閱讀了文檔,但仍然不知道他們想要什么。

其次,我的另一種方法是重寫整個 .json,但隨后我不能將多個人寫入其中(我的 json 是 Person(人)數據庫 - 每個“對象”中的字段很少)。 再次嘗試了更多的東西(例如,將 10 個人放入 List 並將此列表對象(實例)放入 .json 但仍然只有一個人在那里。它需要 Object 參數。

請幫我 :)))

有 3 個主要的庫來處理 json

  1. 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);  

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM