The sequence of calling "put" to build up a JSON tree seems to affect the underlying structure. Not sure if this is by design or not. But it is quite counter-intuitive and contrary to similar APIs. Unit test follows
///////////////////////////////////////
package test;
import org.apache.commons.jxpath.JXPathContext;
import org.junit.Assert;
import org.junit.Test;
import net.sf.json.JSONObject;
public class JsonObjectTest {
JSONObject createOK() {
JSONObject jo = new JSONObject();
jo.put("root", 1);
JSONObject c = new JSONObject();
JSONObject gc = new JSONObject();
c.put("grandchild", gc);
jo.put("child",c);
return jo;
}
JSONObject createBroken() {
JSONObject jo = new JSONObject();
jo.put("root", 1);
JSONObject c = new JSONObject();
jo.put("child",c);
JSONObject gc = new JSONObject();
c.put("grandchild", gc);
return jo;
}
@Test
public void testXX() {
JSONObject broken = createBroken();
JSONObject ok = createOK();
System.out.println(ok.toString()); // Generates: {"root":1,"child":{"grandchild":{}}}
System.out.println(broken.toString()); // Generates: {"root":1,"child":{}}
Assert.assertEquals(createBroken().toString(),createOK().toString());
}
}