Processing json objects in jsp

2020-02-06 04:42发布

问题:

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)%>
<%
}
%>

回答1:

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}


回答2:

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"));


回答3:

The svenson JSON library can also be used from JSP.



回答4:

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.



回答5:

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.