使用Gson封装和解析JSON

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

在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进行封装

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中数据类型一致。

在js中json的定义就是

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

但是由于在java中json就是一段字符串,因此使用Gson进行对象的封装会省去很多不必要的麻烦。

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

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

原文地址:https://www.cnblogs.com/Noctis/p/10610824.html