王國慶 发表于 2024-9-6 08:44:01

SpringMVC-05-Json

1、什么是JSON?

JSON: JavaScript Object Notation(JS 对象描述法)。
JSON 是一种存储和交换数据的语法。
JSON 是通过 JS对象描述法书写的文本,用字面文本的形式来表示一个JS对象
2、为什么要使用JSON?


[*]JSON 是一种轻量级的数据交换格式,伴随着JavaScript语言的火爆,现在使用特别广泛。
[*]采用完全独立于编程语言的文本格式来存储和表示数据。
[*]简洁和清楚的层次结构使得 JSON 成为理想的数据交换语言。
[*]易于人阅读和编写,同时也易于机器剖析和生成,并有效地提升网络传输服从。
3、如何使用JSON?

在 JavaScript 语言中,一切都是对象。因此,任何JavaScript 支持的范例都可以通过 JSON 来表示,比方字符串、数字、对象、数组等。看看它的要求和语法格式:

[*]花括号表示对象
{"name": "MoonDream"}
[*]方括号表示数组
[{"name": "MoonDream"},{"age": 20},{"sex": "男"}]
[*]对象的属性用键值对来表示,多个属性间用逗号分隔
{"name": "MoonDream","age": 20,"sex": "男"}
JSON 和 JavaScript 对象的关系
var obj = {a: 'Hello', b: 'World'}; //这是一个js对象,使用json语法构造,注意键名也是可以使用引号包裹的
var json = '{"a": "Hello", "b": "World"}'; //这是一个 JSON字符串,符合json语法规则,本质是一个字符串JSON 和 JavaScript 对象互转

[*]JSON字符串 -> JavaScript 对象
var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//结果是 {a: 'Hello', b: 'World'}
[*]JavaScript 对象 -> JSON字符串
var json = JSON.stringify({a: 'Hello', b: 'World'});
//结果是 '{"a": "Hello", "b": "World"}'
代码测试

[*]新建一个module ,SpringMVC-05-Json , 添加web的支持
[*]在web目次下新建一个 json-1.html , 编写测试内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON-Test</title>
</head>
<body>



</body>
</html>在IDEA中使用欣赏器打开,检察控制台输出!
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240904222854020-997786372.png
以上只是JSON的简略用法,详细请看 JSON(w3school.com.cn)
4、在SpringMVC中使用JSON

这里我们主要使用两个第三方工具库:Jackson 与 FastJson
Jackson

底子使用


[*]导入jar包
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
[*]配置SpringMVC所需配置
web.xml
<?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>DispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>DispatcherServlet</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>
      <servlet-name>DispatcherServlet</servlet-name>
    </filter-mapping>

</web-app>spring-mvc.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 https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.moondream.controller"/>

    <bean >
      <property name="prefix" value="/WEB-INF/jsp"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans>
[*]编写User实体类,用于测试
package com.moondream.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

//需要导入lombok
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
    private String name;
    private Integer age;
    private String sex;
}
[*]编写Controller,使用Jackson
@Controller
public class UserController {

    @ResponseBody
    @RequestMapping(value = "/json1")
    public String json1() throws JsonProcessingException {
      //创建一个jackson的对象映射器,用来解析数据
      ObjectMapper mapper = new ObjectMapper();

      //创建一个对象
      User user = new User("用户1号", 3, "男");

      //将我们的对象解析成为json格式字符串
      String str = mapper.writeValueAsString(user);
      System.out.println(str);

      return str;
    }

}
[*]配置Tomcat,启动测试
http://localhost:8080/spring05/json1
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240904233719243-89228024.png
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240904233734030-1896879210.png
[*]出现乱码问题,很显着可以看出是发送响应时,编码出现问题。
可以通过@RequestMapping 的 produces 属性 指定该 Handler 响应的内容范例,
详见RequestMapping 中produces 和 consumes
//produces:指定响应的内容类型
@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")
[*]再次测试, http://localhost:8080/spring05/json1 , 乱码问题OK!
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240904235022100-2004759853.png
代码优化


[*]乱码问题
其上使用@RequestMapping 的 produces 属性的方法比较贫苦,如果项目中有很多请求则每一个都要添加。
我们可以在类上也标注一个@RequestMapping,作为方法上@RequestMapping的前置注解。
这样,在这个类中,就不用每次都去处理了。
@Controller
@RequestMapping(produces = "application/json;charset=utf-8")
public class UserController {

    @ResponseBody
    @RequestMapping(value = "/json1")
    public String json1() throws JsonProcessingException {
      //创建一个jackson的对象映射器,用来解析数据
      ObjectMapper mapper = new ObjectMapper();

      //创建一个对象
      User user = new User("用户1号", 3, "男");

      //将我们的对象解析成为json格式字符串
      String str = mapper.writeValueAsString(user);
      System.out.println(str);

      return str;
    }

}
[*]@ResponseBody重复编写问题
与乱码问题解决类似,也是在类上标注@ResponseBody注解,提升作用域。
然后,类上的 @ResponseBody 与 @Controller 可以构成组合注解 @RestController。
类被标注了 @RestController ,就相当于被标注了 @ResponseBody 与 @Controller。
@RestController
@RequestMapping(produces = "application/json;charset=utf-8")
public class UserController {

    @RequestMapping(value = "/json1")
    public String json1() throws JsonProcessingException {
      //创建一个jackson的对象映射器,用来解析数据
      ObjectMapper mapper = new ObjectMapper();

      //创建一个对象
      User user = new User("用户1号", 3, "男");

      //将我们的对象解析成为json格式字符串
      String str = mapper.writeValueAsString(user);
      System.out.println(str);

      return str;
    }

}
启动tomcat测试,结果都正常输出!
测试集合输出

增加一个新的方法
    @RequestMapping(value = "/json2")
    public String json2() throws JsonProcessingException {
      //创建一个jackson的对象映射器,用来解析数据
      ObjectMapper mapper = new ObjectMapper();

      //创建一个对象
      User user1 = new User("用户1号", 4, "男");
      User user2 = new User("用户2号", 3, "女");
      User user3 = new User("用户3号", 2, "武装直升机");
      User user4 = new User("用户4号", 1, "沃尔玛购物袋");
      List<User> list = new ArrayList<>();
      list.add(user1);
      list.add(user2);
      list.add(user3);
      list.add(user4);

      //将我们的对象解析成为json格式
      String str = mapper.writeValueAsString(list);
      System.out.println(str);

      return str;
    }运行结果 : 十分完美,没有任何问题!
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240905233255276-860429512.png
输出时间对象

增加一个新的方法
    @RequestMapping("/json3")
    public String json3() throws JsonProcessingException {
      //创建一个jackson的对象映射器,用来解析数据
      ObjectMapper mapper = new ObjectMapper();

      //创建时间一个对象,java.util.Date
      Date date = new Date();

      //将我们的对象解析成为json格式
      String str = mapper.writeValueAsString(date);
      System.out.println(str);

      return str;
    }运行结果 :
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240905233421589-1369295906.png

[*]默认日期格式会变成一个数字,是1970年1月1日到当前日期的毫秒数!
[*]Jackson 默认是会把时间转成timestamps形式
解决方案:取消timestamps形式 , 自界说时间格式
    @RequestMapping("/json4")
    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();
      String str = mapper.writeValueAsString(date);
      System.out.println(str);

      return str;
    }运行结果 : 成功的输出了相应的格式化时间!
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240905233902300-489085140.png
抽取为工具类

如果要经常使用的话,这样是比较贫苦的,我们可以将这些代码封装到一个工具类中;我们去编写下
package com.moondream.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;
import java.util.Date;

public class JsonUtils {

    public static String getCommonJson(Object object) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(object);
    }

    public static String getDateJson(Date date) throws JsonProcessingException {
      return getDateJson(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getDateJson(Date date, String dateFormat) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
      objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));

      return objectMapper.writeValueAsString(date);
    }

}我们使用工具类,代码就更加简洁了!
    @RequestMapping("/json5")
    public String json5() throws JsonProcessingException {
      Date date = new Date();
      String json = JsonUtils.getDateJson(date);
      System.out.println(json);

      return json;
    }高级使用

我们解决乱码问题和使用 Jackson 也可以在Spring体系内进行。
在 spring-mvc.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 https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.moondream.controller"/>

    <bean >
      <property name="prefix" value="/WEB-INF/jsp"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans><?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 https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.moondream.controller"/>

    <bean >
      <property name="prefix" value="/WEB-INF/jsp"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans><?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 https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.moondream.controller"/>

    <bean >
      <property name="prefix" value="/WEB-INF/jsp"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans><?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 https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.moondream.controller"/>

    <bean >
      <property name="prefix" value="/WEB-INF/jsp"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans><?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 https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.moondream.controller"/>

    <bean >
      <property name="prefix" value="/WEB-INF/jsp"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans><?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 https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.moondream.controller"/>

    <bean >
      <property name="prefix" value="/WEB-INF/jsp"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans>                配置阐明:

[*]:配置一个或多个消息转换器,用于转换@RequestBody方法参数和@ResponseBody方法返回值。
此处提供的消息转换器注册将优先于默认注册的消息转换器。如果要完全关闭默认注册,请参阅register-defaults属性。
[*]StringHttpMessageConverter:用于String值的消息转换器,用来转换字符串编码。
[*]MappingJackson2HttpMessageConverter:Jackson集成的消息转换器,用来将支持的范例(如:实体类、日期、各种集合……)和 JSON字符串 互转。
注意:Spring每次需要使用消息转换器时,只会从消息转换列表中,挑选一个合适的消息转换器执行,多个消息转换器合适,则使用先注册的。
测试:
    @RequestMapping("/json6")
    public String json6() {
      return "中文乱码测试";
    }

    @RequestMapping("/json7")
    public User json7() {
      User user = new User("用户1号", 3, "男");

      return user;
    }

    @RequestMapping("/json8")
    public Date json8() {
      Date date = new Date();

      return date;
    }运行结果:完美无误!
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240906005013035-1208899893.png
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240906005036887-1103388838.png
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240906005055366-1752441787.png
看结果显而易见,
json6处 使用的消息转换器是StringHttpMessageConverter,
因为其最先注册,
而且MappingJackson2HttpMessageConverter仅对响应内容范例为 application/json 的响应体字符串 适配,
此处并不适用;
json7、json8处 使用的消息转换器是MappingJackson2HttpMessageConverter,
本来@ResponseBody方法仅支持寥寥几个范例(即 void、String、ResponseEntity……)作为返回值,
但使用了MappingJackson2HttpMessageConverter之后,可以支持更多的范例作为返回值,
因为MappingJackson2HttpMessageConverter会将返回值都转换成JSON字符串,即String范例,
转换后使用的编码默以为UTF-8。
参考详见:
消息转换器 :: Spring 框架 - Spring 中文 (springframework.org.cn)
HTTP消息转换器MappingJackson2HttpMessageConverter生效的几种方式。- 掘金 (juejin.cn)
FastJson

fastjson.jar是阿里开辟的一款专门用于Java开辟的包,可以方便的实现

[*]JSON对象与JavaBean对象的转换,
[*]JavaBean对象与json字符串的转换,
[*]JSON对象与json字符串的转换。
实现json的转换方法很多,最后的实现结果都是一样的。
pom依靠

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.4</version>
</dependency>三个主要的类


[*]【JSONObject】json对象的类界说化

[*]实现了Map接口,具备Map特性,底层操作由Map实现。
[*]对应json对象,通过各种形式的get()方法可以获取json对象中的数据,也可利用诸如size(),isEmpty()等方法获取”键:值”对的个数和判断是否为空。其本质是通过实现Map接口并调用接口中的方法完成的。

[*]【JSONArray】json对象数组的类界说化

[*]实现了List接口,通过List接口中的方法来完成操作。

[*]【JSON】FastJson中的工具类和各种类的超类

[*]常用于调用各种功能方法,实现转换操作。

代码测试

新建一个FastJsonDemo 类
package com.moondream;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.moondream.pojo.User;

import java.util.ArrayList;
import java.util.List;

public class FastJsonDemo {
    public static void main(String[] args) {
      //创建一个对象
      User user1 = new User("用户1号", 4, "男");
      User user2 = new User("用户2号", 3, "女");
      User user3 = new User("用户3号", 2, "武装直升机");
      User user4 = new User("用户4号", 1, "沃尔玛购物袋");
      List<User> list = new ArrayList<>();
      list.add(user1);
      list.add(user2);
      list.add(user3);
      list.add(user4);

      System.out.println("*******Java对象 转 JSON字符串*******");
      String str1 = JSON.toJSONString(list);
      System.out.println(str1);
      String str2 = JSON.toJSONString(user1);
      System.out.println(str2);

      System.out.println("\n****** JSON字符串 转 Java对象*******");
      User jp_user1 = JSON.parseObject(str2, User.class);
      System.out.println(jp_user1);

      System.out.println("\n****** Java对象 转 JSON对象 ******");
      JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
      System.out.println(jsonObject1.getString("name"));

      System.out.println("\n****** JSON对象 转 Java对象 ******");
      User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
      System.out.println(to_java_user);
    }
}运行结果:
https://img2023.cnblogs.com/blog/3455982/202409/3455982-20240906084651518-265381805.png
这种工具类,我们只需要把握使用就好了,在使用的时候在根据详细的业务去找对应的实现。和以前的commons-io那种工具包一样,拿来用就好了!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: SpringMVC-05-Json