2

I have a JSON object sent from the browser to the jsp page.How do I receive that object and process it in jsp.Do I need any specific parsers? I have used the following piece of code.But it wouldn't work.Essentially I should read the contents of the object and print them in the jsp.

<%@page language="java" import="jso.JSONObject"%>

<%
JSONObject inp=request.getParameter("param1");
%>

<% for(int i=0;i<inp.size();i++)
{%>
    <%=inp.getString(i)%>
<%
}
%>
Sachin Prasad
  • 5,365
  • 12
  • 54
  • 101
user98534
  • 195
  • 3
  • 4
  • 9

5 Answers5

3

My preferred solution to this problem involves using a JSON parser that provides an output that implements the java.util.Map and java.util.List interface. This allows for simple parsing of the JSON structure in the JSP Expression language.

Here is an example using JSON4J provided with Apache Wink. The sample imports JSON data from a URL, parses it in a java scriptlet and browses 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 make this clean, it would be preferable to create a JSTL tag to do the parsing and avoid java scriplet.

<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}
Steve McDuff
  • 338
  • 2
  • 11
1

You can parse the input string to JSONValue and then cast it to JSONOject as like shown below

  JSONObject inp = (JSONObject) JSONValue.parse(request.getParameter("param1"));
Taryn
  • 242,637
  • 56
  • 362
  • 405
skanduku
  • 11
  • 1
0

The svenson JSON library can also be used from JSP.

fforw
  • 5,391
  • 1
  • 18
  • 17
0

You've got several syntax errors in your example code.

First, request.getParameter returns a String, so setting it to a JSONObject won't work. Secondly, your for loop is incomplete.

I suggest looking into the various JSON libraries available for Java and using one of those.

To help get you started, I'd look at some decoding samples.

Mike Cornell
  • 5,909
  • 4
  • 29
  • 38
0

In general, you won't be passing JSON within query parameters -- too much quoting needed. Rather, you should POST with JSON as payload (content type 'application/json') or such.

But beyond this, you need a json parser; Json.org lists tons; my favorite is Jackson, which like most alternatives from the page can also be invoked from jsp.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • u are right.. the value is posted as you say.. but i m not sure how to receive it and process it in the jsp.. – user98534 May 07 '09 at 08:28
  • request.getParameter is the right way to get your payload. Then you need to use a json parser to parse the payload into a JSONObject. – Mike Cornell May 07 '09 at 13:07