Thursday, November 8, 2012

Returning json from jsp

For returning json from jsp you will need the following additional  jars:
   - commons-collections.jar
   - commons-lang.jar
   - ezmorph.jar
   - json-lib.jar

The jsp page will look like:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.*" %>
<%@ page import="net.sf.json.*"%>
<%
try
{
    JSONObject json  = new JSONObject();
    JSONObject person  = new JSONObject();
    JSONArray  persons= new JSONArray();

    person.put("name","abc");
    person.put("address","address1");
    person.put("email","abc@gmail.com");

   persons.add(person);
   
  json.put("persons",persons);

 response.getWriter().write(json.toString());

}catch(Exception e){
}
%>

The above jsp page should return the following json:
{
   "persons":[{
             "name":"abc",
             "address":"address1",
             "email":"abc@gmail.com"
    }]
}