使用Gson封装和解析JSON

案例:判断用户名是否存在html

在jsp页面使用ajax前端

$("#username").change(function(){ var username = $(this).val(); $.get("UserServlet?methodName=whetherHave","username="+username,function(msg){ if(msg==false){ $(".errorMsg").html("用户名可使用"); }else{ $(".errorMsg").html("用户名已经存在"); } },"json"); });

在servlet中使用Gson类来对json进行封装java

protected void whetherHave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); boolean yOn = service.checkUserName(username); Gson gson = new Gson(); String json = gson.toJson(yOn); System.out.println(json); response.getWriter().print(json); }

能够看到在jquery中得到的msg值就是boolean类型的。可见在前端页面中回调函数的参数类型与传入的json中数据类型一致。jquery

在js中json的定义就是ajax

{ "name":"zhangsan","age":18 },json能够是字符串,数值,布尔,null,对象,数组六种。json

可是因为在java中json就是一段字符串,所以使用Gson进行对象的封装会省去不少没必要要的麻烦。数组

注意:json字符串必须使用双引号jsp

https://blog.csdn.net/chenchunlin526/article/details/71173404函数

相关文章
相关标签/搜索