5

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??

Jensen Ching
  • 3,144
  • 4
  • 26
  • 42
Rachit Agrawal
  • 685
  • 4
  • 13
  • 35

2 Answers2

4

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>
Jensen Ching
  • 3,144
  • 4
  • 26
  • 42
  • And afterwards, you should mention methods of embedding that string in a template - usually done simply through an extra set of ` – Andrei Bârsan Oct 30 '12 at 08:21
  • 1
    I added a quick method specifically for Struts 2. – Jensen Ching Oct 30 '12 at 08:22
  • @AndreiBârsan : 1 doubt, using this would convert the json object into string. So in javascript would i still be able to do something like jsonString.data1 , jsonString.data2. – Rachit Agrawal Oct 30 '12 at 08:23
  • @RachitAgrawal use the snippet above that I added :) – Jensen Ching Oct 30 '12 at 08:24
  • @JensenChing : Is there any way to write this Java object without using Gson lib, Actually i have told this can be acomplished using struts2 json pluggin. But I dont know how to do it. – Rachit Agrawal Nov 01 '12 at 12:52
  • It's quite possible, I use it all the time when doing AJAX requests. Check out: http://www.mkyong.com/struts2/struts-2-and-json-example/ for an introduction. Basically in your struts xml you extend from json-default instead of struts-default, then you return a result type of json. This is commonly used with ajax requests, I go the GSON route when it's normally page requests. – Jensen Ching Nov 01 '12 at 15:05
0

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

 jQuery.parseJSON( string );
Community
  • 1
  • 1
Tibor Kiray
  • 108
  • 1
  • 4