在jsp中处理JSON对象 [英] Processing json objects in jsp

查看:1343
本文介绍了在jsp中处理JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从浏览器发送到JSP page.How JSON对象做我收到该对象并处理它jsp.Do我需要任何特定的解析器?我已经使用了下面的一段code.But它不会work.Essentially我应阅读对象的内容,并在jsp打印出来。

 <%@页语言=Java的进口=jso.JSONObject%GT;<%
JSONObject的INP =的request.getParameter(参数1);
%GT;<%的for(int i = 0; I< inp.size();我++)
{%GT;
    &所述;%= inp.getString(ⅰ)%GT;
<%
}
%GT;


解决方案

我的preferred解决这个问题涉及到使用JSON解析器,提供了一个实现的java.util.Map和java.util.List的接口输出。这使得在JSP防爆pression语言的JSON结构简单的解析。

下面是使用提供和Apache Wink JSON4J一个例子。从URL样本进口JSON数据,解析它在Java小脚本和浏览所产生的结构。

  c为C:进口VAR =dataJsonURL =HTTP://localhost/request.json/>
<%
JSON字符串=(字符串)pageContext.getAttribute(dataJson);
pageContext.setAttribute(parsedJSON,org.apache.commons.json.JSON.parse(JSON));
%GT;
获取节点的名称索引1:$ {parsedJSON.node [1]。名称}

为使这种清洁,这将是preferable创建JSTL标签做解析和避免的Java scriplet。

  c为C:进口VAR =dataJsonURL =HTTP://localhost/request.json/>
< JSON:解析JSON =$ {} dataJsonV​​AR =parsedJSON/>
获取节点的名称索引1:$ {parsedJSON.node [1]。名称}

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

解决方案

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}

这篇关于在jsp中处理JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆