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??
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With