1.什麼是JSON
- JSON(JavaScript Object Notation, JS 對象簡譜) 是一種輕量級的數據交換格式
- 採用完全獨立於編程語言的文本格式來存儲和表示數據
- 簡潔和清晰的層次結構使得 JSON 成爲理想的數據交換語言
- 易於人閱讀和編寫,同時也易於機器解析和生成
- 有效地提升網絡傳輸效率
2.JSON 與 JS 對象的關係
JSON 是 JS 對象的字符串表示法,它使用文本表示一個 JS 對象的信息,本質是一個字符串。
//這是一個對象,注意鍵名也是可以使用引號包裹的
let obj = {a: 'Hello', b: 'World'};
//這是一個 JSON 字符串,本質是一個字符串
let json = '{"a": "Hello", "b": "World"}';
3.JSON 和 JS 對象互轉
要實現從JSON字符串轉換爲JS對象,使用 JSON.parse() 方法:
var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//結果是 {a: 'Hello', b: 'World'}
要實現從JS對象轉換爲JSON字符串,使用 JSON.stringify() 方法:
var json = JSON.stringify({a: 'Hello', b: 'World'});
//結果是 '{"a": "Hello", "b": "World"}'
4.代碼實現
1、新建一個項目,添加web支持
2、在web目錄下新建一個json1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON_劉洋</title>
</head>
<body>
<script type="text/javascript">
//編寫一個js的對象
let user = {
name:"liuyang",
age:3,
sex:"girl"
};
//將js對象轉換成json字符串
let str = JSON.stringify(user);
console.log(str);
//將json字符串轉換爲js對象
let user2 = JSON.parse(str);
console.log(user2.age,user2.name,user2.sex);
</script>
</body>
</html>
3、在瀏覽器打開,看控制檯輸出
4.1 Controller返回JSON數據
字符串解析成爲json格式
1、導包
<!--Servlet - JSP -->
<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>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--數據庫驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
2、配置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>
<!--2、亂碼過濾器-->
<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>
3、配置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">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<!-- 自動掃描指定的包,下面所有註解類交給IOC容器管理 -->
<context:component-scan base-package="com.yang.controller"/>
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 後綴 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
4、在applicationContext中導入springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<context:component-scan base-package="com.yang.controller"/>
<import resource="classpath:springmvc-servlet.xml"/>
</beans>
5、實體類
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//需要導入lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
6、控制類
package com.yang.controller;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yang.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class JsonController {
@RequestMapping("/j1")
public String json1(){
return "string";
}
@RequestMapping("/j2")
public String json2(){
return "{\"name\":\"劉洋\",\"age\":3,\"sex\":\"girl\"}";
}
}
7、配置tomcat測試
出現亂碼問題
8、解決亂碼問題
在springmvc-servlet.xml中加入StringHttpMessageConverter轉換配置,注意改變頭文件
<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格式
@RequestMapping("/o1")
public String json3() throws JsonProcessingException {
//創建一個jackson的對象映射器,用來解析數據
ObjectMapper mapper = new ObjectMapper();
//創建一個對象
User user = new User("劉洋", 3, "女");
//將我們的對象解析成爲json格式
String str = mapper.writeValueAsString(user);
//由於@ResponseBody註解,這裏會將str轉成json格式返回;十分方便
return str;
}
集合解析成爲json格式
@RequestMapping("/o2")
public String json4() throws JsonProcessingException {
ObjectMapper mapper1 = new ObjectMapper();
User user = new User("劉洋", 3, "女");
User user1 = new User("劉洋", 3, "女");
User user2 = new User("劉洋", 3, "女");
User user3 = new User("劉洋", 3, "女");
User user4 = new User("劉洋", 3, "女");
User user5 = new User("劉洋", 3, "女");
List<User> users = Arrays.asList(user, user1, user2, user3, user4, user5);
return mapper1.writeValueAsString(users);
}
4.2 fastJson
fastJson是阿里巴巴出品的一個json序列化工具,首先也要導入依賴。之前的pom依賴已經寫過了,這裏就不寫了。
fastjson 三個主要的類:
【JSONObject 代表 json 對象 】
JSONObject實現了Map接口, 猜想 JSONObject底層操作是由Map實現的。
JSONObject對應json對象,通過各種形式的get()方法可以獲取json對象中的數據,也可利用諸如size(),isEmpty()等方法獲取"鍵:值"對的個數和判斷是否爲空。其本質是通過實現Map接口並調用接口中的方法完成的。
【JSONArray 代表 json 對象數組】
內部是有List接口中的方法來完成操作的。
【JSON 代表 JSONObject和JSONArray的轉化】
JSON類源碼分析與使用
仔細觀察這些方法,主要是實現json對象,json對象數組,javabean對象,json字符串之間的相互轉化。
代碼實現:
@RequestMapping("/fast1")
public String fastj() throws JsonProcessingException {
User user = new User("劉洋", 3, "女");
User user1 = new User("劉洋", 3, "女");
User user2 = new User("劉洋", 3, "女");
User user3 = new User("劉洋", 3, "女");
User user4 = new User("劉洋", 3, "女");
User user5 = new User("劉洋", 3, "女");
List<User> users = Arrays.asList(user, user1, user2, user3, user4, user5);
System.out.println("*******Java對象 轉 JSON字符串*******");
String jsonString = JSON.toJSONString(users);
System.out.println(jsonString);
// System.out.println("=====================");
// System.out.println("\n****** JSON字符串 轉 Java對象*******")
// List<User> list = JSON.parseObject(jsonString, List.class);
// System.out.println(list);
return jsonString;
}
頁面返回JSON字符串
控制檯輸出JSON字符串