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
Java API

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

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

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

 String jsonText = jObject.toJSONString();

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


<body onload="loadJsonObject()">
<h2>Simple JSON Example</h2>
<table border="1" width="100%">
 <td>Employee Id</td>
 <td><span id="jId"></span</td>
 <td><span id="jName"></span></td>
 <td><span id="jSalary"></span></td>
 <td>Is Permananet</td>
 <td><span id="jParmanent"></span></td>
 <td><span id="jNickname"></span></td>

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 and set it to classpath.