Processing json objects in jsp
I have a JSON object sent from browser to jsp page. How to get this object and process it in jsp.Do I need any specific parsers? I used the following piece of code. But that won't work. Maybe I should read the content of the object and print it to jsp.
<%@page language="java" import="jso.JSONObject"%>
<%
JSONObject inp=request.getParameter("param1");
%>
<% for(int i=0;i<inp.size();i++)
{%>
<%=inp.getString(i)%>
<%
}
%>
a source to share
My preferred solution to this problem is to use a JSON parser which provides output that implements the java.util.Map and java.util.List interface. This makes it easy to parse the JSON structure in the JSP expression language.
Here's an example using JSON4J with Apache Wink. The sample imports JSON data from a URL, parses it into Java script, and walks through the resulting structure.
<c:import var="dataJson" url="http://localhost/request.json"/>
<%
String json = (String)pageContext.getAttribute("dataJson");
pageContext.setAttribute("parsedJSON", org.apache.commons.json.JSON.parse(json));
%>
Fetch the name of the node at index 1 : ${parsedJSON.node[1].name}
To keep this clean, it would be preferable to create a JSTL tag for parsing and avoid java script.
<c:import var="dataJson" url="http://localhost/request.json"/>
<json:parse json="${dataJson}" var="parsedJSON" />
Fetch the name of the node at index 1 : ${parsedJSON.node[1].name}
a source to share
In general, you won't be passing JSON within request parameters - too much quoting is needed. Rather, you should be using POST with JSON as payload (content type "application / json") or such.
But beyond that, you need a json parser; Json.org lists tons; my favorite is Jackson which like most page alternatives can also be called from jsp.
a source to share