zoukankan      html  css  js  c++  java
  • 使用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

  • 相关阅读:
    ajax优缺点
    关于测量专业软件使用感受及建议
    12.7
    12.6
    场景调研
    对搜狗输入法的看法及建议
    12.9
    12.8
    12.5站立会议
    12.4站立会议
  • 原文地址:https://www.cnblogs.com/Noctis/p/10610824.html
Copyright © 2011-2022 走看看