Monday, November 5, 2012

How to iterate Java object in JavaScript using JSON?


You may require passing a java object to javascript and iterating through it. Java object could be literally anything whether it List, Map, List of Map, Map of List etc.
For example: ArrayList<String>, Hashtable<String,String>, ArrayList<Hashtable<String,String>>, Hashtable<String,ArrayList<String>> etc.

This can be easily achieved using JSON. To run below JSP you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

About the example: In below example I have created a java object i.e. HashMap<String, ArrayList<String>>. Add some values to the object. Convert the object into JSON string using method JSONValue.toJSONString(). In JavaScript pass the JSON string to JSON.parse() and get the corresponding JavaScript object. Now you are ready to iterate it using below syntax. Please see the self explanatory example below.




Note: For javascript you may get error 'JSON' is undefined in IE, to resolve it download json2.js from below link and add to your file.
https://github.com/douglascrockford/JSON-js

Syntax:
<script type="text/javascript" src="json2.js"></script>