Вопрос

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?

Это было полезно?

Решение

Другие советы

You want to use JSONObject to create a map of keys to any arbitrary value, including JSONArrays or even other JSONObjects.

If all your data objects know how to convert themselves to a JSONObject (or whatever), you can assemble your tree of objects and call toJSON on the root node. That populates the "flat" members and creates your "children" JSONArray with the results of the sub-task toJSON() calls.

It's basic tree recursion. Of course, if your data isn't already structured that way, this doesn't help much.

public interface JSONThing {
    public JSONObject toJSON();
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top