在 Java 中创建一个 JSON 对象并在 javascript/jquery 中访问它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13135035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a JSON object in Java and accessing it in javascript/jquery
提问by Rachit Agrawal
I want to create a JSON object in java code and then pass it on to javascript/jquery for parsing(further processing). I am using Struts 2 framework.
我想在 java 代码中创建一个 JSON 对象,然后将它传递给 javascript/jquery 进行解析(进一步处理)。我正在使用 Struts 2 框架。
This has to be done at page load, not after a AJAX call. How to access the JSON object (created in java) in javascript/jquery.
这必须在页面加载时完成,而不是在 AJAX 调用之后完成。如何在 javascript/jquery 中访问 JSON 对象(在 java 中创建)。
Also are any API's for creating JSON object for java object??
还有用于为 java 对象创建 JSON 对象的任何 API 吗?
采纳答案by Jensen Ching
You should check out the Google GSONlibrary.
您应该查看Google GSON库。
To convert an Object to a JSON string is as simple as:
将对象转换为 JSON 字符串非常简单:
Gson gson = new Gson();
String jsonString = gson.toJson(myObject);
For your use case (Struts 2), a simple solution would be to place the jsonString
property in your Action
, then refer to it in the JSP page as follows:
对于您的用例(Struts 2),一个简单的解决方案是将jsonString
属性放在您的 中Action
,然后在 JSP 页面中引用它,如下所示:
<!-- this goes into your .jsp -->
<script type="text/javascript">
var myJsonObject = <s:property value="jsonString" default="[]" escape="false" />;
</script>