Skip to content

Instantly share code, notes, and snippets.

@madan712
Created November 5, 2012 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madan712/4017166 to your computer and use it in GitHub Desktop.
Save madan712/4017166 to your computer and use it in GitHub Desktop.
Iterate Java object in JavaScript using JSON
<%@ page language="java" import="java.util.*,org.json.simple.JSONValue"%>
<%
HashMap<String, ArrayList<String>> country = new HashMap<String, ArrayList<String>>();
ArrayList<String> city = new ArrayList<String>();
city.add("Mumbai");
city.add("Delhi");
city.add("kolkata");
country.put("India", city);
city = new ArrayList<String>();
city.add("London");
city.add("Manchester");
city.add("Bristol");
country.put("England", city);
String jCountry = JSONValue.toJSONString(country);
System.out.println("jCountry >> " + jCountry);
%>
<html>
<head>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
<!--
function readJavaObject() {
var jCountry = '<%=jCountry%>';
var countryObj = JSON.parse(jCountry);
for(i in countryObj) {
//get the map
for(j=0;j<countryObj[i].length;j++) {
//iterate each item of list
alert(i+" "+countryObj[i][j]);
}
}
}
//-->
</script>
</head>
<body onload="readJavaObject();">
How to iterate Java object in Javascript using JSON?
<br>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment