将 Java 对象转换为 JSON?

2022-01-16 00:00:00 json jquery javascript struts2

我使用 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.

相关文章