Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a JSON object in Java and accessing it in javascript/jquery

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.

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.

Also are any API's for creating JSON object for java object??

like image 212
Rachit Agrawal Avatar asked Oct 07 '22 04:10

Rachit Agrawal


1 Answers

You should check out the Google GSON library.

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

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:

<!-- this goes into your .jsp -->
<script type="text/javascript">
    var myJsonObject = <s:property value="jsonString" default="[]" escape="false" />; 
</script>
like image 88
Jensen Ching Avatar answered Oct 10 '22 03:10

Jensen Ching