Home > OS >  How to add subnode to json file using json-simple
How to add subnode to json file using json-simple

Time:10-16

I create json file with the folloing code:

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

OUTPUT:

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

How can I add content of java map to the this json output as a new node sothat I have at the end the following output:

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

CodePudding user response:

You just need to add another object of type JsonObject and it will do that

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

And that will return the output what you want

In case you need add more fields without a object a good practice its do the next:

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

This return:

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

  • Related