Thursday, March 01, 2007

Simplest way to return a JSON object using data from a Spring bean

I had a need to return a JSON object using data from a Spring bean. I decided the simplest way was to use a servlet. It took me a little while, so I thought I'd post what I learned for the benefit of all. Note I am using the JSON-simple library (http://www.json.org/java/simple.txt). One key to making this work is to set the content type to "text/plain":

package com.myco;

import com.myco.domain.MyBizObj;
import com.myco.domain.MyFacade;
import java.io.*;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class JsonServlet extends HttpServlet
{
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
WebApplicationContext context =
WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

MyFacade instance = (HistoryFacade) context.getBean("myFacade");
List myobjs = instance.getMyBizObjs(); // Use generics if you like

response.setContentType("text/plain;charset=UTF-8");

PrintWriter out = response.getWriter();

if (myobjs.size()>0)
{
JSONArray array=new JSONArray();
for (MyBizObj a : myobjs)
{
JSONObject obj=new JSONObject();
obj.put("name", a.getScreenname());
obj.put("name", a.getEmailaddr());
array.add(obj);
}
out.println(array.toString());
}
else
{
JSONObject obj=new JSONObject();

obj.put("valid","false");
out.println(obj.toString());
}
out.close();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}

public String getServletInfo()
{
return "Short description";
}
}

You will need to set up your Spring context in the usual way.

1 comment:

Nick said...

JSON Objects and Arrays have a constructor that take a bean (or a collection of beans) and use reflection to populate the field/value pairs.

I think you could just get away with out.println(new JSONArray(myobjs).toString());