Search code examples
javaorg.json

Generating complex treelike JSON responses


I have some Java code that will print out JSON from a Servlet:

JSONArray arrayObj = new JSONArray();
arrayObj.put("MCA");
arrayObj.put("Amit Kumar");
arrayObj.put("19-12-1986");
arrayObj.put(24);
arrayObj.put("Scored");
arrayObj.put(new Double(66.67));
PrintWriter out = response.getWriter();
out.println(arrayObj);

will print out a page in a browser that looks like:

["MCA","Amit Kumar","19-12-1986",24,"Scored",66.67]

I need to be able to generate more complex, treelike data structures such as

[{
task:'Project: Shopping',
duration:13.25,
user:'Tommy Maintz',
iconCls:'task-folder',
expanded: true,
children:[{
    task:'Housewares',
    duration:1.25,
    user:'Tommy Maintz',
    iconCls:'task-folder',
    children:[{
        task:'Kitchen supplies',
        duration:0.25,
        user:'Tommy Maintz',
        leaf:true,
        iconCls:'task'
    },{
        task:'Groceries',
        duration:.4,
        user:'Tommy Maintz',
        leaf:true,
        iconCls:'task'
    },{
        task:'Cleaning supplies',
        duration:.4,
        user:'Tommy Maintz',
        leaf:true,
        iconCls:'task'
    },{
        task: 'Office supplies',
        duration: .2,
        user: 'Tommy Maintz',
        leaf: true,
        iconCls: 'task'
    }]
}, {
    task:'Remodeling',
    duration:12,
    user:'Tommy Maintz',
    iconCls:'task-folder',
    expanded: true,
    children:[{
        task:'Retile kitchen',
        duration:6.5,
        user:'Tommy Maintz',
        leaf:true,
        iconCls:'task'
    },{

are there any methods or techniques with the org.json API I can use to generate this treelike JSON response? Specifically, I'm wondering if there's anything I can use to handle the creation of expanded nodes, children, and leaf nodes?


Solution

  • You might like the approach described here: http://betasoftware.posterous.com/how-to-write-compact-json-objects-in-java