2015-07-20 119 views
2

在Java中,我有一個像下面將自定義對象的地圖轉換爲json對象?

Map<String, List<Employee>> = new HashMap<String, List<Employee>>(); 

我需要將上面的地圖轉換成JSON對象是一個HashMap

我試了一下: -

使用jsonObject代替HashMapJsonArray而不是list

com.amazonaws.util.json.JSONObject jsonObject = new com.amazonaws.util.json.JSONObject(); 
com.amazonaws.util.json.JsonArray empList = new JsonArray(); 
empList.add(empObject) 
jsonObject.put("some String", empList); 

然後在請求屬性

request.setAttribute("empMap", jsonObject.toString()); 

添加jsonObject但是當我找回它在JavaScript我得到的JSONObject

{emp_10:[[email protected]]} 

的價值正如你可以在上面看到我得到的價值[email protected]不是它的性能爲何如此?

也沒有更好的方法,我可以自定義對象Map<String, List<Employee>>以JSON對象的HashMap的轉換,而無需使用替代HashMap和JsonArray,而不是名單 的JSONObject?

我使用已經在我的項目庫下方,打開即可使用,如果需要

Jettison Library (org.codehaus.jettison.json.JSONObject) 
json-lib(net.sf.json.JSONObject) 
apache json library (com.amazonaws.util.json.JSONObject) 
+1

實現toString(),因爲它似乎默認的toString被調用和返回 – vinayakj

+0

你需要重寫toString方法 – Zion

+0

@ user3198603對象引用 - 你檢查了我的答案嗎?它對你有用嗎? – nikhil

回答

0

我認爲你需要有在Java的最終額外的輔助功能的新

public JSONObject asJSON(Employee employee) { 
    ObjectMapper mapper = new ObjectMapper(); 
    return new JSONObject(mapper.writeValueAsString(employee)); 
} 

和代替在以下添加empObject,添加更新後的值asJSON(empObject)

empList.add(empObject) 

此外,刪除.toString()

request.setAttribute("empMap", jsonObject.toString());