1.对象和Json之间的转换
<1>对象--->字符串: JsonObject jsonObject=JsonObject.fromObject(对象);
<2>字符串-->对象:
①.JsonObject jsonObject=JsonObject.fromObject(字符串);
②.对象=jsonObject.toBean(jsonObject,对象.class);
2.对象集合和字符串之间的转换
<1>对象集合--->字符串
JsonArray jsonArray=JsonArray.fromObject(对象集合);
<2>字符串---->对象集合
JsonArray jsonArray=JsonArray.fromObject(字符串);
对象集合=jsonArray.toCollection(jsonArray);
3.在JSP中使用Json
在jsp页面引入json.js文件
<1>Json.stringify(对象)----->将JS对象转换成Json字符串
<2>Json.parse-------->将Json字符串转成Js对象
代码实例:(连接数据库进行判断,由于时间问题,所以我就放了两个比较重要的代码上来了,其他的util、bean之类的类,相信以大家的能力不成问题的)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录</title>
<script type="text/javascript" src="jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function User(uname,upwd){
this.uname=uname;
this.upwd=upwd;
}
$(function(){
$("#bt").click(function(){
var uname=$("#uname").val();
var upwd=$("#upwd").val();
var jsonString=JSON.stringify(new User(uname,upwd));
$.post(
"login.do",
{
"jsonString":jsonString
},
function(data){
if(data=="true"){
location.href="index.jsp";
}else{
alert("账号或者密码错误");
}
}
);
});
});
</script>
</head>
<body>
<table>
<tr><td>账号:<input type="text" name="uname" id="uname"></td></tr>
<tr><td>密码:<input type="text" name="upwd" id="upwd"></td></tr>
<tr><td><input type="submit" value="登录" id="bt"></td></tr>
</table>
</body>
</html>
Java代码:
package com.zking.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zking.biz.UserBiz;
import com.zking.biz.UserBizImp;
import com.zking.entity.User;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
public class LoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String jsonString=req.getParameter("jsonString");
JSONObject jsonObject=JSONObject.fromObject(jsonString);
User u=(User) JSONObject.toBean(jsonObject, User.class);
UserBiz ub=new UserBizImp();
boolean b=ub.getLogin(u.getUname(), u.getUpwd());
PrintWriter pw=resp.getWriter();
if(b){
pw.write("true");
pw.close();
}else{
pw.write("false");
pw.close();
}
}
}