• Jackson的使用


    一、Controller返回JSON数据

    • Jackson应该是目前比较好的json解析工具了
    • 当然工具不止这个,比如还有阿里巴巴的fastjson等等。
    • 们这里使用Jackson,使用它需要导入它的jar包;
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.3</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 配置SpringMVC需要的配置
      web. xmI
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>SpringMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>SpringMVC</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <filter>
            <filter-name>encoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>utf-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    springmvc-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!--自动扫描包-->
        <context:component-scan base-package="com.massimo.controller"/>
    
        <!--视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            <!--前缀-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--后缀-->
            <property name="suffix" value=".jsp"/>
        </bean>
    
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 编写一个User的实体类,然后去编写测试Controller;
      User实体类:
    package com.massimo.pojo;
    
    public class User {
        private String name;
        private int age;
        private String sex;
    
        public User() {
        }
    
        public User(String name, int age, String sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    UserController:

    package com.massimo.controller;
    
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.massimo.pojo.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class UserController {
    
        @RequestMapping("/j1")
        @ResponseBody //加了这个注解,它就不会走视图解析器,会直接返回一个字符串
        public String json1() throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
    
            //创建一个对象
            User user = new User("马西莫",20,"男");
            String str = mapper.writeValueAsString(user);
            return str;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 配置Tomcat,启动测试

    在这里插入图片描述

    • 发现出现了乱码问题,我们需要设置一下他的编码格式为utf-8, 以及它返回的类型;
    • 通过@RequestMaping的produces属性来实现,修改下代码
    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
    
    • 1
    • 再次测试,效果如下:
      在这里插入图片描述

    二、代码优化

    乱码统一解决

    上一种方法比较麻烦,如果项目中有许多请求则每一个都要添加,可以通过Spring配置统一指定,这样就不用每次都去处理了!

    我们可以在springmvc的配置文件上添加一段消息StringHttpMessageConverter转换配置!

    <!--JSON乱码问题配置-->
        <mvc:annotation-driven>
            <mvc:message-converters register-defaults="true">
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                            <property name="failOnEmptyBeans" value="false"/>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    不用@RequestMaping的produces属性来测试,效果如下:
    在这里插入图片描述
    @Controller与@RestController的区别:

    • @Controller会走视图解析器
    • @RestController会返回字符串

    三、测试

    3.1、集合测试

    @RequestMapping("/j2")
        @ResponseBody
        public String json2() throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            List<User> userList = new ArrayList<User>();
    
            User user1 = new User("Massimo1", 20, "男");
            User user2 = new User("Massimo2", 20, "男");
            User user3 = new User("Massimo3", 20, "男");
            User user4 = new User("Massimo4", 20, "男");
    
            userList.add(user1);
            userList.add(user2);
            userList.add(user3);
            userList.add(user4);
    
            String str = mapper.writeValueAsString(userList);
            return str;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    效果:
    在这里插入图片描述

    3.2、时间测试一

     @RequestMapping("/j3")
        @ResponseBody
        public String json3() throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            Date date = new Date();
            //自定义日期的格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //ObjectMapper,时间解析后的默认格式为:Timestamp,时间戳
            return mapper.writeValueAsString(sdf.format(date));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    效果:
    在这里插入图片描述

    3.3、时间测试二

    @RequestMapping("/j4")
        @ResponseBody
        public String json4() throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            //不使用时间戳的方式
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
            //自定义日期的格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mapper.setDateFormat(sdf);
            Date date = new Date();
            //ObjectMapper,时间解析后的默认格式为:Timestamp,时间戳
            return mapper.writeValueAsString(date);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    效果:
    在这里插入图片描述

    3.4、封装工具类

    package com.massimo.utils;
    
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    import java.text.SimpleDateFormat;
    
    public class JsonUtils {
        
        public static String getJson(Object object){
            return getJson(object,"yyyy-MM-dd HH:mm:ss");
        }
        
        public static String getJson(Object object,String dateFormat){
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            mapper.setDateFormat(sdf);
    
            try {
                return mapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
  • 相关阅读:
    异行星依赖管理系统显示面板与数据过滤设置
    【开发问题&解决方法记录】01.dian
    djangoMTV初探
    【云原生】-Docker容器迁移Oracle到MySQL
    将STM32 内部Flash虚拟成优盘,进行IAP升级
    6.对象的实例化内存布局与访问定位
    IntelliJ IDE 插件开发指南
    树莓派的常用系统配置
    力扣 -- 10. 正则表达式匹配
    黑豹程序员-架构师学习路线图-百科:Knife4j API接口文档管理
  • 原文地址:https://blog.csdn.net/Massimo__JAVA/article/details/125558132