January 22, 2010

Responding to JSON in your server-side JSP script

I wanted to implement some open API for JSON clients. It took me an two days to finish it, Javascript&JSP gives me a pain in the neck. :(

Below is the example code to responding to JSON in a server-side JSP script. It shows how to set up the JSON text, HTTP header and jsoncallback. I hope you don't waste time.

<%@ page language="java" import="net.sf.json.JSONObject" %>
<%@page import="java.util.*" %>

    JSONObject object=new JSONObject();
    object.put("key", "value");

    String jsoncallback = request.getParameter("jsoncallback");
    response.getWriter().println(jsoncallback + "(" + object.toString()+");");


  1. Anonymous7/1/11 02:40

    thanks a million. I didn't need the JSONObject, just put the JSON-data instead of object.toString()

  2. i'm glad I could help :) as you said, just putting the JSON data is also OK bc JSON is a text-based language.