zoukankan      html  css  js  c++  java
  • 【SpringMVC】09 对JSON的应用

    前面JavaWeb的JSON回顾:

    https://www.cnblogs.com/mindzone/p/12820877.html

    上面的这个帖子我都还没有实际写进Servlet使用,要Mark一下了


    我们配置一个演示的Bean

    package cn.dai.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @author ArkD42
     * @file SpringMVC
     * @create 2020 - 05 - 07 - 15:06
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Person {
        private String name;
        private Integer age;
        private Boolean gender;
    }

    编写控制器

    @Controller
    public class JsonController {
    
        @GetMapping("/json01")
        public String json01(Model model){
    
            Person person = new Person("阿强", 22, true);
    
    
            model.addAttribute("msg",person.toString());
    
            return "test";
        }
    }

    测试我们的响应结果是否会乱码

    然后导入Maven坐标

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.11.0</version>
            </dependency>

    使用Jackson

    package cn.dai.controller;
    
    import cn.dai.pojo.Person;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    
    import java.util.Arrays;
    
    
    /**
     * @author ArkD42
     * @file SpringMVC
     * @create 2020 - 05 - 07 - 15:06
     */
    @Controller
    public class JsonController {
    
        @GetMapping("/json01")
        public String json01(Model model) throws JsonProcessingException {
    
            Person person = new Person("阿强", 22, true);
    
            ObjectMapper objectMapper = new ObjectMapper();
    
            String s = objectMapper.writeValueAsString(person);
    
            model.addAttribute("msg", Arrays.toString(new String[]{s,"
    ",person.toString()}));
    
            return "test";
        }
    }

    访问测试

    注意要记得再Web包里面导入Jackson的依赖,

    不然会出现找不到Bean异常

    测试单个的JSON返回

    也是没有问题的,不过这样我也就没有办法演示JSON乱码的问题了

    针对JSON乱码的问题,可以使用一个Produces属性

    是@RequestMapping注解中的属性

    或者使用SpringMVC原生xml配置

    Bean方式配置,如果无效,可以尝试放在注解驱动的外面

    <?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
    "
    >
        <!-- 目录扫描的方式注册Bean -->
        <context:component-scan base-package="cn.dai.controller" />
        <!-- 默认的Servlet处理器 不处理静态资源-->
        <mvc:default-servlet-handler />
        <!-- MVC 注解驱动支持-->
        <mvc:annotation-driven>
    
            <!-- 解决JSON乱码 -->
            <mvc:message-converters>
    
                <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>
    
        <!-- 视图解析器 -->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
        </bean>
    
    </beans>

    对时间的JSON转换,这是使用LocalDateTime的API

        @GetMapping("/json02")
        public String json02(Model model) throws JsonProcessingException {
    
            ObjectMapper objectMapper = new ObjectMapper();
    
            LocalDateTime now = LocalDateTime.now();
            System.out.println(now);
    
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
    
            String format = dateTimeFormatter.format(now);
    
            String nows = objectMapper.writeValueAsString(now);
    
            objectMapper.writeValueAsString(format);
    
            model.addAttribute("msg", "时间转换测试");
            model.addAttribute("now", now);
            model.addAttribute("nows", nows);
            model.addAttribute("format", format);
    
            /*
            时间转换测试
            2020-05-07T16:03:07.177
            {"month":"MAY","year":2020,"dayOfYear":128,"dayOfMonth":7,"hour":16,"minute":3,"monthValue":5,"nano":177000000,"second":7,"dayOfWeek":"THURSDAY","chronology":{"id":"ISO","calendarType":"iso8601"}}
            2020-5-7
             */
    
            return "time";
        }

    然后是原生Date & SimpleDateFormat

        @GetMapping("/json03")
        public String json03(Model model) throws JsonProcessingException {
            ObjectMapper objectMapper = new ObjectMapper();
    
            Date date = new Date();
    
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
            String format = simpleDateFormat.format(date);
            
            objectMapper.writeValueAsString(format);
            
            return "time";
        }

    Fastjson

    Maven坐标

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.68</version>
    </dependency>
        @GetMapping("/json04")
        public String json04(Model model) {
    
            String s = JSON.toJSONString(new Date());
    
            model.addAttribute("msg", s);
            return "time";
        }
  • 相关阅读:
    php数组到json的转变
    微信小程序获取微信绑定的手机号
    微信小程序授权登录
    用海豚框架(DolphinPHP)实现单/多图片上传时,如何获得图片路径
    数据库索引-简单了解
    php将二维数组转换成我想要的一维数组
    php的八大数据类型
    单例模式
    Springboot配置Sqlserver
    WinForm 文件操作
  • 原文地址:https://www.cnblogs.com/mindzone/p/12843209.html
Copyright © 2011-2022 走看看