Friday, April 20, 2012

Java Examples for JSON encoding

JSON (JavaScript Object Notation) is a lightweight data-interchange format. JSON is syntax for storing and exchanging text information same like XML. JSON is smaller than XML, and faster and easier to parse.

To know more about JSON, visit http://www.json.org/
Java API http://www.json.org/java/

Json can be used to commincate between Java & Javascript and vice versa. Lets see a simple self explanatory example.

About the example :
A simple JSP page which contains Java instance of JSONObject. This object is converted to String and passed to eval() function in javascript to convert into JSONObject object in Javascript.

To run below example you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

<%@ page import="org.json.simple.JSONObject" %>
<%
 JSONObject jObject = new JSONObject();

 jObject.put("EmployeeId",new Integer(121));
 jObject.put("Name","Ramesh");  
 jObject.put("Salary",new Double(15000.00));
 jObject.put("isPermanent",new Boolean(true));
 jObject.put("Nickname",null);

 String jsonText = jObject.toJSONString();

 System.out.println("jsonText :: "+jsonText);
%>
<html>
<head>
<script type="text/javascript">
 function loadJsonObject()
 {
  var JSONObject = eval('(<%= jsonText %>)');

  document.getElementById("jId").innerHTML=JSONObject.EmployeeId;
  document.getElementById("jName").innerHTML=JSONObject.Name;
  document.getElementById("jSalary").innerHTML=JSONObject.Salary;
  document.getElementById("jParmanent").innerHTML=JSONObject.isPermanent;
  document.getElementById("jNickname").innerHTML=JSONObject.Nickname;

 }
</script>
</head>
<body onload="loadJsonObject()">
<h2>Simple JSON Example</h2>
<p>
<table border="1" width="100%">
<tr>
 <td>Employee Id</td>
 <td><span id="jId"></span</td>
</tr>
<tr>
 <td>Name</td>
 <td><span id="jName"></span></td>
</tr>
<tr>
 <td>Salary</td>
 <td><span id="jSalary"></span></td>
</tr>
<tr>
 <td>Is Permananet</td>
 <td><span id="jParmanent"></span></td>
</tr>
<tr>
 <td>Nickname</td>
 <td><span id="jNickname"></span></td>
</tr>
</table>
</body>
</html>

Output :






Note : If you get mentioned errors.
  • Only a type can be imported. org.json.simple.JSONObject resolves to a package
  • JSONObject cannot be resolved to a type
Crosscheck if json-simple-1.1.1.jar is set in classpath. Simply add the JAR file to ${Tomcat}/lib/ folder. Please download json-simple-1.1.1.jar file from http://code.google.com/p/json-simple/ and set it to classpath.