Search code examples
javajsonjson-lib

JSON Nested data creation failing in Java


import net.sf.json.*;

public class JSONDemo {

/**
 * @param args
 */
public static void main(String[] args) {
    JSONObject mainObj = new JSONObject();

    JSONObject jObj1 = new JSONObject();
    JSONObject jObj2 = new JSONObject();

    JSONArray jA1 = new JSONArray();        
    JSONArray jA2 = new JSONArray();

    JSONArray mainArray= new JSONArray();

    jObj1.accumulate("id", 17);
    jObj1.accumulate("name", "Alex");
    jObj1.accumulate("children", jA1);

    mainArray.add(jObj1);

    jObj2.accumulate("id", 94);
    jObj2.accumulate("name", "Steve");
    jObj2.accumulate("children", jA2);

    //Adding the new object to jObj1 via jA1

    jA1.add(jObj2);

    mainObj.accumulate("ccgs", mainArray);
    System.out.println(mainObj.toString());     
}    

}

The output I got is

{"ccgs":[{"id":17,"name":"Alex","children":[]}]}

I wanted the jObj2 within the children key of jObj1.


Solution

  • Apparently the node creation order has an impact on the generated string. If you change the object creation order, beginning with the children, the Json is correct.

    See that code :

        public static void main(String[] args) {
            // first create the child node
            JSONObject jObj2 = new JSONObject();
            jObj2.accumulate("id", 94);
            jObj2.accumulate("name", "Steve");
            jObj2.accumulate("children", new JSONArray());
    
            // then create the parent's children array
            JSONArray jA1 = new JSONArray(); 
            jA1.add(jObj2);
    
            // then create the parent
            JSONObject jObj1 = new JSONObject();
            jObj1.accumulate("id", 17);
            jObj1.accumulate("name", "Alex");
            jObj1.accumulate("children", jA1);
    
            // then create the main array
            JSONArray mainArray = new JSONArray();
            mainArray.add(jObj1);
    
            // then create the main object
            JSONObject mainObj = new JSONObject();
            mainObj.accumulate("ccgs", mainArray);
    
            System.out.println(mainObj);    
        }
    

    The output is :

    {"ccgs":[{"id":17,"name":"Alex","children":[{"id":94,"name":"Steve","children":[]}]}]}