• SpringMVC 学习(七)JSON


    9. JSON

    9.1 简介

    JSON(JavaScript Object Notation,JS 对象标记)是一种轻量级数据交换格式,采用独立于编程语言的文本格式储存和表示数据,易于机器解析和生成,提升网络传输效率。

    任何 JavaScript 支持的数据类型都可以通过 JSON 表示,例如字符串、数字、对象、数组等。

    JSON 键值对保存 JavaScript 对象,键:值 对组合中的键名在前用双引号 "" 包裹,值在后,两者使用冒号 : 分隔。

    {"name": "弗罗多"}
    {"age": "50"}
    {"sex": "男"}
    
    • 1
    • 2
    • 3
    • JSON 是 JavaScript 对象的字符串表示法,使用文本表示一个 JS 对象,本质是一个字符串。

      var obj = {a: 'Hello', "b": 'World'}; // JS 对象
      var json = '{"a": "Hello", "b": "World"}'; // JSON 字符串
      
      • 1
      • 2
    • 使用 JSON.stringify() 方法可将 JavaScript 对象转换为JSON字符串

      var json = JSON.stringify({a: 'Hello', b: 'World'});
      // json = '{"a": "Hello", "b": "World"}'
      
      • 1
      • 2
    • 使用 JSON.parse() 方法可将 JSON 字符串转换为 JS 对象。

      var obj = JSON.parse('{"a": "Hello", "b": "World"}'); 
      // obj = {a: 'Hello', b: 'World'}
      
      • 1
      • 2

    9.2 Controller 返回 JSON

    (1) jackson

    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <version>2.10.0version>
    dependency>
    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.10.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    注意:新导入依赖时发布的lib目录下引入依赖

    (2) 中文乱码

    • @RequestMapping 注解 produces 属性解决中文乱码
    @Controller
    public class UserController {
        // produces 设置编码格式,解决中文乱码
        @RequestMapping(value = "/testResJson", produces = "application/json;charset=utf-8")
        // 不被视图解析器解析,返回JSON字符串
        @ResponseBody
        public String testResJson() throws JsonProcessingException {
            User user = new User("弗罗多", 50, "男");
            ObjectMapper mapper = new ObjectMapper();
            // 将对象转换为 JSON
            return mapper.writeValueAsString(user);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • Spring MVC 配置解决中文乱码问题
    
    <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
    • 测试
    @Controller
    public class UserController {
    
        // produces 设置编码格式,解决乱码
        @RequestMapping(value = "/testResJson")
        // 不被视图解析器解析,返回字符串
        @ResponseBody
        public String testResJson() throws JsonProcessingException {
            User user = new User("弗罗多", 50, "男");
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(user);
        }
    
        @RequestMapping(value = "/testResMoreJson")
        @ResponseBody
        public String testResMoreJson() throws JsonProcessingException {
            List<User> userList = new ArrayList<User>();
            User frodo = new User("弗罗多", 50, "男");
            User sam = new User("山姆", 50, "男");
            User aragon = new User("阿拉贡", 50, "男");
            userList.add(frodo);
            userList.add(sam);
            userList.add(aragon);
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(userList);
        }
    
        @RequestMapping("/testResTimeJson")
        @ResponseBody
        public String testResTimeJson() throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            //不使用时间戳的方式
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            //自定义日期格式对象
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:dd:ss");
            //指定日期格式
            mapper.setDateFormat(simpleDate);
            Date date = new Date();
    
            // java 时间格式控制
            // String formatDate = simpleDate.format(date);
    
            return  mapper.writeValueAsString(date);
        }
    }
    
    • 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

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    • 抽取为工具类
    public class JsonUtil {
    
        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

    (3) FastJson

    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>fastjsonartifactId>
        <version>1.2.70version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @RequestMapping(value = "/testFastJson")
    @ResponseBody
    public String testFastJson() throws JsonProcessingException {
    
        List<User> userList = new ArrayList<User>();
        User frodo = new User("弗罗多", 50, "男");
        User sam = new User("山姆", 50, "男");
        User aragon = new User("阿拉贡", 50, "男");
        userList.add(frodo);
        userList.add(sam);
        userList.add(aragon);
        
        System.out.println("*******Java对象 转 JSON字符串*******");
            String str1 = JSON.toJSONString(userList);
            System.out.println("JSON.toJSONString(list)==>"+str1);
            String str2 = JSON.toJSONString(frodo);
            System.out.println("JSON.toJSONString(frodo)==>"+str2);
            System.out.println("\n****** JSON字符串 转 Java对象*******");
            User jp_user1=JSON.parseObject(str2,User.class);
            System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
    
            System.out.println("\n****** Java对象 转 JSON对象 ******");
            JSONObject jsonObject1 = (JSONObject) JSON.toJSON(sam);
            System.out.println("(JSONObject) JSON.toJSON(sam)==>"+jsonObject1.getString("name"));
    
            System.out.println("\n****** JSON对象 转 Java对象 ******");
            User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
            System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
        
        return JSON.toJSONString(userList);
    }
    
    • 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

    在这里插入图片描述

    在这里插入图片描述

  • 相关阅读:
    咪咕MGV2000KL南传_S905L3B_MT7668线刷固件包
    asp.net core mvc之路由
    Java知识体系索引
    MySQL(5)
    信息检索 | 常见专类信息检索系统一览
    Python解析参数的三种方法
    性能测试 - 理论
    Django 表单
    java-php-python-ssm-在线学习辅导与答疑系统-计算机毕业设计
    蚂蚁集团、浙江大学联合发布开源大模型知识抽取框架OneKE
  • 原文地址:https://blog.csdn.net/qq_42651415/article/details/133265798