2011-12-21 71 views
0

我有一些Java代碼將從一個Servlet打印出JSON:生成複雜的樹狀JSON響應

[「MCA:

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

將在看起來像一個瀏覽器打印出頁面」, 「阿米特庫馬爾」, 「19-12-1986」,24, 「刻痕」,66.67]

我需要能夠生成更復雜的,樹狀數據結構,例如

[{ 
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' 
    },{ 

是否有任何方法或技術可用於生成此樹狀JSON響應的org.json API?具體來說,我想知道是否有任何東西可以用來處理擴展節點,子節點和葉節點的創建?

+0

還有其他的API已經爲Tree結構提供了更好的支持。例如。傑克遜(http://wiki.fasterxml.com/JacksonHome)或Gson(http://sites.google.com/site/gson/gson-user-guide)。 – proko 2011-12-21 19:23:30

回答

2

你想使用JSONObject來創建一個任意值的鍵映射,包括JSONArrays甚至其他JSONObjects。

0

如果您的所有數據對象知道如何將自己轉換爲JSONObject(或其他),你可以組裝你的對象的樹的根節點上調用toJSON 。填充「扁平」成員並創建子任務toJSON()調用的結果「子女」JSONArray

這是基本的樹遞歸。當然,如果你的數據還沒有以這種方式構建,這沒有多大幫助。

public interface JSONThing { 
    public JSONObject toJSON(); 
}