如何使用 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));
 //...

这将return输出你想要的

如果您需要在没有对象的情况下添加更多字段,请执行下一步:

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

这个return:

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