JSON — not just for AJAX

Mar 12th, 20071 Comment

I recently blogged on the evils of mixing Java and JavaScript in JSP pages but didn’t give any good ways around it.  I mean, you have a list or array in Java and you want JavaScript in the JSP page to access this data — how do you do that?

Let me introduce you to to Json-lib.

You’ve probably heard of JSON before and people rant and rave about it on using JSON with AJAX instead of XML[1].  And I don’t think there is anything wrong it that, but I didn’t want or need AJAX — I just need to move data from Java to JavaScript in a JSP page.  And JSON makes it oh so easy.

  1. In your Servlet, get and arrange your data the way you like it.
  2. Then using Json-lib make a JSONObject like so: JSONObject jsMap = JSONObject.fromObject(jobsMap);.
  3. Put the string of that JSON object into your request.  You know what I mean: request.setAttribute("JSON_MAP",jsMap.toString());.
  4. In your JSP page, just eval that string: var jobMap = eval(<%= request.getAttribute("JSON_MAP");%>.

And that’s it — your structure has been transfered from Java to JavaScript with no fuss nor muss.

The Json-lib jar is actually quite small. But the bad thing is that it has quite a few dependencies that their page doesn’t explain well and that doesn’t come with the download.  I needed to grab commons-beanutils, commons-logging, and ezmorph to get things rolling with Json-lib.  But it has sure been worth it.
[1] Then should it be called AJAJ?

One Response to “JSON — not just for AJAX”

  1. almiray says:

    Mike, Json-lib is built using maven, and as such it includes a page where all the required dependencies are listed (http://json-lib.sourceforge.net/dependencies.html)

    Good to know you found Json-lib helpful =)

Leave a Reply

You must be logged in to post a comment.