問題描述
我使用 struts2 做 Action 和 jquery 做 UI ...
I am using struts2 for Action and jquery for UI ...
我想知道如何將 Map 對象轉換為 JSON 對象并將其發送回 UI,
I want to know how to convert a Map object to JSON object and send it back to UI ,
現在可以在 JSP 頁面中打印普通的 java Map 對象了:
Now am able to print it in JSP page the normal java Map object :
{71=Heart XXX, 76=No Heart YYY}
但我希望它是這樣的:
{71:Heart XXX, 76:No Heart YYY}
我將如何實現這一目標....?
How will i achieve this .... ?
推薦答案
試試 Gson:
Gson gson = new Gson();
String json = gson.toJson(yourMap);
不過,我不建議將這種代碼放入 JSP 中.像這樣的東西應該存在于像 Servlet 或 Action 類這樣的控制器中.
I wouldn't recommend putting this kind of code into a JSP, though. Things like these should live in a controller like a Servlet or Action class.
你也絕對不希望輸出是:
You also most definitely don't want the output to be:
{71:Heart XXX, 76:No Heart YYY}
而是像正確的 JSON(帶引號的名稱,帶引號的字符串值):
but rather proper JSON like (quoted names, quoted string values):
{"71":"Heart XXX", "76":"No Heart YYY"}
Gson 會輸出后者.
Gson will output the latter.
這篇關于將 Java 對象轉換為 JSON?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!