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

1

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

6 Comments

And afterwards, you should mention methods of embedding that string in a template - usually done simply through an extra set of <script> tags defining a variable containing the JSON.
I added a quick method specifically for Struts 2.
@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.
@RachitAgrawal use the snippet above that I added :)
@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.
|
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 );

1 Comment

the variable i want to use is a class variable of action class, It wouldnt be directly accesible in Javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.