一、概述
- JSON(JavaScript Object Notation, JS对象标记)是一种轻量级的数据交换格式,目前使用特别广泛。
- 采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得JSON成为理想的数据交换语言。
- 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
在 JavaScript 语言中,一切都是对象。因此,任何JavaScript 支持的类型都可以通过 JSON 来表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:
- 对象表示为键值对,数据由逗号分隔
- 花括号保存对象
- 方括号保存数组
JSON 键值对是用来保存 JavaScript 对象的一种方式,和 JavaScript 对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 “” 包裹,使用冒号 : 分隔,然后紧接着值:
{"name": "SongQX"}
{"age": "3"}
{"sex": "男"}
很多人搞不清楚 JSON 和 JavaScript 对象的关系,甚至连谁是谁都不清楚。其实,可以这么理解:
JSON 是 JavaScript 对象的字符串表示法(因此,才能被前端的Vue和React解析),它使用文本表示一个 JS 对象的信息,本质是一个字符串。
<script type="text/javascript">
var user = {
name : "松崎乡",
age : "20" ,
sex : "男"
}
console.log(user) ;
var str = JSON.stringify(user) ;
console.log(str) ;
var obj = JSON.parse(str) ;
console.log(obj) ;
</script>
二、Controller返回JSON数据
Jackson应该是目前比较好的json解析工具了,用来将后台返回来的java对象转化为JSON字符串
我们这里使用Jackson,使用它需要导入它的jar包;
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
配置好SpringMVC需要的环境 :
1、配置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>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>
</web-app>
2、配置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">
<context:component-scan base-package="com.sqx.controller"/>
<mvc:default-servlet-handler />
<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、配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Json和Ajax笔记</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Json篇</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
Controller测试
@Controller
public class JsonController {
@RequestMapping("/json1")
@ResponseBody
public String json1() throws JsonProcessingException {
System.out.println("成功进入请求");
ObjectMapper objectMapper = new ObjectMapper() ;
User user = new User("松崎乡", 20, "男");
String str = objectMapper.writeValueAsString(user);
return str ;
}
}
@Controller + @ResponseBody == @RestController
**测试结果: **
1、JSON数据出现乱码问题
发现结果乱码了{“name”:"???",“age”:20,“sex”:"?"},如何解决?
1、方法一
修改@RequestMapping即可
@RequestMapping(value="/json2",produces = "application/json;charset=utf-8")
缺点:每次请求都需要设置,麻烦
2、方法二
乱码统一解决,在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>
如果我们json是返回的数组或集合我们可以用https://www.sojson.com/解析JSON的格式
2、时间格式问题
默认我们的mapper会将时间Date解析为一个时间戳,我们需要为其设置时间格式
@RequestMapping(value="/time4")
@ResponseBody
public String json4() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper() ;
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false) ;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-SS");
objectMapper.setDateFormat(simpleDateFormat);
Date date = new Date();
String str = objectMapper.writeValueAsString(date);
return str ;
}
结果
三、编写工具类
我们发现代码复用太多,封装一个工具类
public class JsonUtils {
public static String getJson(Object obj){
ObjectMapper objectMapper = new ObjectMapper() ;
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false) ;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-SS");
objectMapper.setDateFormat(simpleDateFormat);
String str = null;
try {
str = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return str ;
}
public static String getJson(Object obj,String sdf){
ObjectMapper objectMapper = new ObjectMapper() ;
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false) ;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(sdf);
objectMapper.setDateFormat(simpleDateFormat);
String str = null;
try {
str = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return str ;
}
}
工具类测试
@RequestMapping(value="/time5")
@ResponseBody
public String json5() throws JsonProcessingException {
Date date = new Date();
String str = JsonUtils.getJson(date);
return str ;
}
大功告成!完美!
|