簡體   English   中英

如何使用json-simple將子節點添加到json文件

[英]How to add subnode to json file using json-simple

我使用以下代碼創建 json 文件:

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
   public static void main(String args[]) {
      //Creating a JSONObject object
      JSONObject jsonObject = new JSONObject();
      //Inserting key-value pairs into the json object
      jsonObject.put("ID", "1");
      jsonObject.put("First_Name", "Shikhar");
      
      try {
         FileWriter file = new FileWriter("E:/output.json");
         file.write(jsonObject.toJSONString());
         file.close();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      System.out.println("JSON file created: "+jsonObject);
   }
}

輸出:

JSON file created: {
"First_Name":"Shikhar",
"ID":"1"}

如何將 java 映射的內容作為新節點添加到此 json 輸出中,以便最后得到以下輸出:

  JSON file created: {
    "First_Name":"Shikhar",
    "ID":"1",
      "data": {
        "a": "Test1",
        "b": "Test2"
         }
        }

您只需要添加另一個 JsonObject 類型的對象,它就會這樣做

 //...
      jsonObject.put("ID", "1");
      jsonObject.put("First_Name", "Shikhar");
      jsonObject.put("data", new JSONObject(data));
 //...

這將返回您想要的輸出

如果您需要在沒有對象的情況下添加更多字段,請執行以下操作:

JSONObject mainFields = new JSONObject();
mainFields.put("id", "1");
JSONObject secondFields = new JSONObject();
secondFields.put("field1", "some cool");
secondFields.put("field2", "not cool");
mainFields.put("data", secondFields);

這個回報:

{
 "id":"1",
 "data":{
   "field1": "some cool",
   "field2": "not cool"
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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