Spring MVC:Json交互
- 1、什么是Json
- 2、环境搭建
- 3、json解析工具
-
- 3.1、使用Jackson
-
- pom.xml导入Jackson依赖:
- 创建一个实体类
- 编写一个Controller
-
- 运行结果
- json乱码问题解决
-
- 1、通过@RequestMaping的produces属性来解决
- 2、通过Spring配置统一指定
- List集合测试
-
- 运行结果
- 打印时间戳
-
- 运行结果
- 3.2、使用FastJson
-
- pom.xml导入FastJson依赖:
- springmvc-servlet.xml:
- 编写一个Controller
-
- 运行结果:
- Fastjson的几个方法:
- 4、可能会遇到的问题: 500错误
1、什么是Json
概念:
- JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
- JSON是轻量级的文本数据交换格式
- JSON 独立于语言:JSON 使用 Javascript语法来描述数据对象,但是 JSON仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多 不同的编程语言。 目前非常多的动态(PHP,JSP,.NET)编程语言都支持JSON。
-
JSON 具有自我描述性,更易理解
json语法规则
名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值:
- 数据在名称/值对中
- 数据由逗号分隔
- 大括号 {} 保存对象
-
中括号 [] 保存数组数组可以包含多个对象
更多了解
2、环境搭建
pom.xml
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--SpringMVC所需导入的包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.19.RELEASE</version>
</dependency>
<!--servlet所需导入的包-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--工具-->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
<build>
<!--在build中配置resource,来防止资源导出失败问题-->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<!--指定maven编译的jdk版本和编译(防止乱码)-->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins </groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
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">
<!--1.注册servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
<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>
<!--所有请求都会被springmvc拦截 -->
<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>
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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.xxx.controller"/>
<!-- 让Spring MVC不处理静态资源 如: HTML . JS . CSS . 图片 , 视频 ..... -->
<!--<mvc:default-servlet-handler />-->
<!--
支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<!--<mvc:annotation-driven />-->
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
3、json解析工具
3.1、使用Jackson
Java生态圈中有很多处理JSON和XML格式化的类库,Jackson是其中比较著名的一个。
pom.xml导入Jackson依赖:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
创建一个实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private Integer age;
private String sex;
}
编写一个Controller
//@RestController
@Controller
public class ControllerJsonTest01 {
@RequestMapping("/json/t1")
@ResponseBody
public String jsonTest01() throws JsonProcessingException {
ObjectMapper mapper=new ObjectMapper();
User user=new User("男一号",21,"男");
String str=mapper.writeValueAsString(user);
return str;
}
@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中。
@RestController注解,相当于@Co[email protected]两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了。
运行结果
出现了乱码问题
json乱码问题解决
1、通过@RequestMaping的produces属性来解决
//produces:指定响应体返回类型和编码
@RequestMapping(value = "/json/t1",produces = "application/json;charset=utf-8")
2、通过Spring配置统一指定
在springmvc-servlet.xml文件中添加
<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>
List集合测试
//@Controller
@RestController
public class ControllerJsonTest01 {
// @RequestMapping(value = "/json/t2",produces = "application/json;charset=utf-8")
@RequestMapping("/json/t2")
public String jsonTest02() throws JsonProcessingException {
ObjectMapper mapper=new ObjectMapper();
List<User> userList=new ArrayList<User>();
User user1=new User("男一号",21,"男");
User user2=new User("男二号",22,"男");
User user3=new User("男三号",23,"男");
User user4=new User("男四号",21,"男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
String str=mapper.writeValueAsString(userList);
return str;
}
运行结果
打印时间戳
@RequestMapping("/json/t3")
public String jsonTest03() 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);
return str;
}
运行结果
3.2、使用FastJson
是由阿里巴巴工程师基于JAVA开发的一款JSON解析器和生成器,可用于将Java对象转换为其JSON表示形式。它还可以用于将JSON字符串转换为等效的Java对象。
pom.xml导入FastJson依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
springmvc-servlet.xml:
<!-- 开启mvc注解并设置编码格式,并且设置Fastjson支持 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- @ResponseBody乱码问题,将StringHttpMessageConverter的默认编码设为UTF-8 -->
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"/>
</bean>
<!-- 配置Fastjson支持 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="charset" value="UTF-8" />
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<value>QuoteFieldNames</value>
<value>WriteMapNullValue</value>
<value>WriteDateUseDateFormat</value>
<value>WriteEnumUsingToString</value>
<value>DisableCircularReferenceDetect</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Fastjson的SerializerFeature序列化属性:
QuoteFieldNames 输出key时是否使用双引号,默认为true
WriteMapNullValue 是否输出值为null的字段,默认为false
WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null
WriteDateUseDateFormat Date的日期转换器
DisableCircularReferenceDetect 解决FastJson循环引用的问题避免出现{“r e f " : " ref”:“ref”:".rows[0].user"}
编写一个Controller
@RequestMapping("/json/t4")
public String jsonTest04() {
ObjectMapper mapper=new ObjectMapper();
List<User> userList=new ArrayList<User>();
User user1=new User("男一号",21,"男");
User user2=new User("男二号",22,"男");
User user3=new User("男三号",23,"男");
User user4=new User("男四号",21,"男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
String str=JSON.toJSONString(userList);
return str;
运行结果:
Fastjson的几个方法:
创建一个FastJsonDemo类
public class FastJsonDemo {
public static void main(String[] args) {
//创建一个对象
User user1 = new User("1号", 3, "男");
User user2 = new User("2号", 3, "男");
User user3 = new User("3号", 3, "男");
User user4 = new User("4号", 3, "男");
List<User> list = new ArrayList<User>();
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("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+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(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+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);
}
}
4、可能会遇到的问题: 500错误
如果确定自己的代码没有什么问题,那么不妨检查自己lib包有没有所需的jar包
没有的话,添加
一个在线的json工具https://www.sojson.com/json/