• 吴裕雄天生自然Spring BootSpring Boot处理JSON数据


        在Spring Boot的Web应用中,内置了JSON数据的解析功能,默认使用Jackson自动完成解析(不需要加载Jackson依赖包),当控制器返回一个Java对象或集合数据时,Spring Boot自动将其转换成JSON数据,使用起来很方便简洁。
    Spring Boot处理JSON数据时,需要用到两个重要的JSON格式转换注解,分别是@RequestBody和@ResponseBody。
    @RequestBody:用于将请求体中的数据绑定到方法的形参中,该注解应用在方法的形参上。
    @ResponseBody:用于直接返回JSON对象,该注解应用在方法上。
        下面通过一个实例讲解Spring Boot处理JSON数据的过程,该实例针对返回实体对象、ArrayList集合、Map<String, Object>集合以及List<Map<String, Object>>集合分别处理。
    Spring Boot处理JSON数据的过程。
    1.创建实体类
    2.创建视图页面
    3.创建控制器
    4.运行
    创建实体类
    
    应用的com.ch.ch5_2.model包中,创建实体类Person。具体代码如下:
    package com.ch.ch5_2.model;
    public class Person {
        private String pname;
        private String password;
        private Integer page;
        //省略set和get方法
    }
    创建视图页面
    
    应用的src/main/resources/templates目录下,创建视图页面input.html。在input.html页面中,引入jQuery框架,并使用它的ajax方法进行异步请求。
    创建控制器
    
    应用的com.ch.ch5_2.controller包中,创建控制器类TestJsonController。在该类中有两个处理方法,一个是界面导航方法input,一个是接收页面请求的方法。
    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.json</groupId>
        <artifactId>SpringBootJson</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.0.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <!-- 声明项目配置依赖编码格式为 utf-8 -->
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <fastjson.version>1.2.24</fastjson.version>
        </properties>
    
        <dependencies>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    server.servlet.context-path=/ch5_2
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
    <!-- 默认访问 src/main/resources/static下的css文件夹-->
    <link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
    <!-- 引入jQuery -->
    <script type="text/javascript" th:src="@{js/jquery.min.js}"></script>
    <script type="text/javascript">
        function testJson() {
            //获取输入的值pname为id
            var pname = $("#pname").val();
            var password = $("#password").val();
            var page = $("#page").val();
            alert(password);
            $.ajax({
                //发送请求的URL字符串
                url : "testJson",
                //定义回调响应的数据格式为JSON字符串,该属性可以省略
                dataType : "json",
                //请求类型
                type : "post",
                //定义发送请求的数据格式为JSON字符串
                contentType : "application/json",
                //data表示发送的数据
                data : JSON.stringify({pname:pname,password:password,page:page}),
                //成功响应的结果
                success : function(data){
                    if(data != null){
                        //返回一个Person对象
                        //alert("输入的用户名:" + data.pname + ",密码:" + data.password + ",年龄:" +  data.page);
                        //ArrayList<Person>对象
                        /**for(var i = 0; i < data.length; i++){
                            alert(data[i].pname);
                        }**/
                        //返回一个Map<String, Object>对象
                        //alert(data.pname);//pname为key
                        //返回一个List<Map<String, Object>>对象
                        for(var i = 0; i < data.length; i++){
                            alert(data[i].pname);
                        }
                    }
                },
                //请求出错
                error:function(){
                    alert("数据发送失败");
                }
            });
        }
    </script>
    </head>
    <body>
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">处理JSON数据</h3>
            </div>
        </div>
        <div class="container">
            <div>
                <h4>添加用户</h4>
            </div>
            <div class="row">
                <div class="col-md-6 col-sm-6">
                    <form class="form-horizontal" action="">
                        <div class="form-group">
                            <div class="input-group col-md-6">
                                <span class="input-group-addon">
                                    <i class="glyphicon glyphicon-pencil"></i>
                                </span>
                                <input class="form-control" type="text"
                                 id="pname" th:placeholder="请输入用户名"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="input-group col-md-6">
                                <span class="input-group-addon">
                                    <i class="glyphicon glyphicon-pencil"></i>
                                </span>
                                <input class="form-control" type="text"
                                 id="password" th:placeholder="请输入密码"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="input-group col-md-6">
                                <span class="input-group-addon">
                                    <i class="glyphicon glyphicon-pencil"></i>
                                </span>
                                <input class="form-control" type="text"
                                 id="page" th:placeholder="请输入年龄"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-6">
                                <div class="btn-group btn-group-justified">
                                    <div class="btn-group">
                                        <button type="button" onclick="testJson()" class="btn btn-success">
                                            <span class="glyphicon glyphicon-share"></span>
                                            &nbsp;测试
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
    </html>
    package com.ch.ch5_2.model;
    
    public class Person {
        private String pname;
        private String password;
        private Integer page;
    
        public String getPname() {
            return pname;
        }
    
        public void setPname(String pname) {
            this.pname = pname;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Integer getPage() {
            return page;
        }
    
        public void setPage(Integer page) {
            this.page = page;
        }
    }
    package com.ch.ch5_2.controller;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.ch.ch5_2.model.Person;
    
    @Controller
    public class TestJsonController {
        /**
         * 进入视图页面
         */
        @RequestMapping("/input")
        public String input() {
            return "input";
        }
    
        @RequestMapping("/testJson")
        @ResponseBody
        /*
         * @RestController注解相当于@ResponseBody + @Controller合在一起的作用。 1)
         * 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面或者html,
         * 返回的内容就是Return的内容。 2)
         * 如果需要返回到指定页面,则需要用 @Controller注解。如果需要返回JSON,XML或自定义mediaType内容到页面,
         * 则需要在对应的方法上加上@ResponseBody注解。
         */
        public List<Map<String, Object>> testJson(@RequestBody Person user) {
            // 打印接收的JSON格式数据
            System.out.println("pname=" + user.getPname() + ", password=" + user.getPassword() + ",page=" + user.getPage());
            // 返回Person对象
            // return user;
            /**
             * ArrayList<Person> allp = new ArrayList<Person>(); Person p1 = new Person();
             * p1.setPname("陈恒1"); p1.setPassword("123456"); p1.setPage(80); allp.add(p1);
             * Person p2 = new Person(); p2.setPname("陈恒2"); p2.setPassword("78910");
             * p2.setPage(90); allp.add(p2); //返回ArrayList<Person>对象 return allp;
             **/
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("pname", "陈恒2");
            map.put("password", "123456");
            map.put("page", 25);
            // 返回一个Map<String, Object>对象
            // return map;
            // 返回一个List<Map<String, Object>>对象
            List<Map<String, Object>> allp = new ArrayList<Map<String, Object>>();
            allp.add(map);
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("pname", "陈恒3");
            map1.put("password", "54321");
            map1.put("page", 55);
            allp.add(map1);
            return allp;
        }
    }
    package com.ch.ch5_2;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Ch52Application {
        public static void main(String[] args) {
            SpringApplication.run(Ch52Application.class, args);
        }
    }

     

  • 相关阅读:
    Robberies
    Big Event in HDU
    UVA 562 Dividing coins
    Little Rooks
    Bone Collector
    Piggy-Bank
    0-1背包问题之——饭卡
    Monkey and Banana
    The Triangle
    Burning Midnight Oil
  • 原文地址:https://www.cnblogs.com/tszr/p/15315474.html
Copyright © 2020-2023  润新知