在Java中创建JSON对象并在javascript / jquery中访问它

时间:2021-03-01 15:56:41

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?

2 个解决方案

#1


4  

You should check out the Google GSON library.

您应该查看Google GSON库。

To convert an Object to a JSON string is as simple as:

将Object转换为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>

#2


0  

You could try this POST for the question library. As for consuming the json string in javascript you can use jQuery

您可以在问题库中尝试此POST。至于在javascript中使用json字符串,你可以使用jQuery

 jQuery.parseJSON( string );

#1


4  

You should check out the Google GSON library.

您应该查看Google GSON库。

To convert an Object to a JSON string is as simple as:

将Object转换为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>

#2


0  

You could try this POST for the question library. As for consuming the json string in javascript you can use jQuery

您可以在问题库中尝试此POST。至于在javascript中使用json字符串,你可以使用jQuery

 jQuery.parseJSON( string );