记得以前写过一篇关于生成json字符串的java类,因为用的比较少,所以也没有深究,最近学习EXT,在它的使用中也着重提到了json,于是决定好好学习一下,此外还有另外一个原因,那就是xml解析有时确实有点繁琐....
以前的java类是参考.net版的json类写出来的,我返回过json字符串,但一直没有发现其中的问题,今天在学习时终于发现原有的类中有一点小小的问题:
下面是修正后的java类:
package com.zb.database.util;
import java.util.ArrayList;
public class Json {
public static void main(String[] args) {
}
public String singleInfo="";
protected boolean _success=true;
protected String _error="";
protected ArrayList arrData=new ArrayList();
protected ArrayList dataItem=new ArrayList();
public String getError() {
return _error;
}
public void setError(String error) {
if(!error.equals(""))this._success=false;
this._error = error;
}
public boolean getSuccess() {
return _success;
}
public void setSuccess(boolean success) {
if(success) this._error="";
this._success = success;
}
public Json()
{
}
public void reSet()
{
arrData.clear();
dataItem.clear();
}
public void addItem(String name,String _value)
{
dataItem.add(name);
dataItem.add(_value);
}
//一个数组添加完毕,一个新的数组开始
public void addItemOk()
{
arrData.add(dataItem);
dataItem=new ArrayList();
}
public String ToString()
{
StringBuilder sb=new StringBuilder();
sb.append("{");
sb.append("\"datas\":");
sb.append("[");
int ad=arrData.size();
for(int i=0;i<ad;i++)
{
ArrayList arr=(ArrayList)(arrData.get(i));
sb.append("{");
int t=arr.size();
for(int j=0;j<t;j+=2)
{
if(j==t) break;
sb.append("\"");
sb.append(arr.get(j).toString());
sb.append("\"");
sb.append(":");
sb.append("\"");
sb.append(arr.get(j+1).toString());
sb.append("\"");
if(j<t-2) sb.append(",");
}
sb.append("}");
if(i<ad-1) sb.append(",");
}
sb.append("]");
sb.append("}");
return sb.toString();
}
}
类中本来有一个:_success、_error的,是一组标记,但感觉在实际中没什么很大的作用,于是在生成字符串时去掉了,在原有的类中,我没有把所有的键名都用双引号引起来,后来在解析时出了问题,于是都给加上了,此外,原来为了输出整齐好看,我故意加入了<br>,这算是一个致命错误了,在实际中根本不需要用alert输出整个json字符串对象的值的,而且那只是为了跟踪输出的一个特例而已,真是有点画蛇添足的味道...
下面我们结合数据库来写一个输出json字符串的jsp文件:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="com.zb.database.util.DB,java.sql.*,com.zb.database.util.Json" %>
<%
response.setContentType("text/html");
out.clear();
out.clearBuffer();
DB db=new DB();
Connection conn=db.getSQLConnection();
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from product ");
Json json=new Json();
json.reSet();
json.setSuccess(true);
while(rs.next())
{
json.addItem("a",(new Integer(rs.getInt(1))).toString());
json.addItem("b",rs.getString(2));
json.addItem("c",rs.getString(3));
json.addItem("d",(new Integer(rs.getInt(4))).toString());
json.addItem("e",rs.getDate(5).toString());
json.addItem("f",rs.getString(6));
json.addItemOk();
}
out.println(json.ToString());
%>
接下来我们用prototype实现ajax来测试结果:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>prototype测试 ajax测试</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<script language="javascript" src="js/prototype.js"></script>
<script>
function sendRequest() {
var url = "
http://localhost:8088/json/testgetjson.jsp";
var mailAjax = new Ajax.Request(
url,
{
method: 'get',
onComplete: jsonResponse
}
);
}
function jsonResponse(originalRequest) {
var div=document.getElementById("getrequest");
var jsondiv=document.getElementById("jsondiv");
div.innerHTML= originalRequest.responseText;
jsondiv.innerHTML = originalRequest.responseText.
evalJSON(true).datas[0].a;
}
</script>
<body>
<div id="getrequest">
</div>
<br><br>
<div id="jsondiv">Ok
</div>
<input type="submit" name="smt" id="smt" value="发送请求" onclick="sendRequest()">
<br>
</body>
</html>