做java這么久了居然還不知道JSON的使用(一文帶你了解)
- JSON(JavaScript Object Notation, NS對(duì)象標(biāo)記)是一種輕量級(jí)的數(shù)據(jù)交換格式,目前使用特別廣泛。
- 采用完全獨(dú)立于編程語(yǔ)言的 文本格式 來(lái)存儲(chǔ)和表示數(shù)據(jù)。
- 簡(jiǎn)潔和清晰的層次結(jié)構(gòu)使得JSON成為理想的數(shù)據(jù)交換語(yǔ)言。
- 易于人閱讀和編寫(xiě),同時(shí)也易于機(jī)器解析和生成,并有效地提升網(wǎng)絡(luò)傳輸效率。
在JavaScript語(yǔ)言中,一切都是對(duì)象。因此,任何JavaScript 支持的類型都可以通過(guò)JSON來(lái)表示,例如字符串、數(shù)字、對(duì)象、數(shù)組等。看看他的要求和語(yǔ)法格式:
- 對(duì)象表示為鍵值對(duì),數(shù)據(jù)由逗號(hào)分隔
- 花括號(hào)保存對(duì)象
- 方括號(hào)保存數(shù)組
JSON鍵值對(duì)是用來(lái)保存JavaScript對(duì)象的一種方式,和JavaScript對(duì)象的寫(xiě)法也大同小異,鍵/值對(duì)組合中的鍵名寫(xiě)在前面并用雙引號(hào) “” 包裹,使用冒號(hào) : 分隔,然后緊接著值:
{"name":"zhangsan"}
{"age":"3"}
{"sex":"男"}
JSON是JavaScript對(duì)象的字符串表示法,它使用文本表示一個(gè)JS對(duì)象的信息,本質(zhì)是一個(gè)字符串。
var obj = {a:'Hello',b:'World'};//這是一個(gè)對(duì)象,注意鍵名也是可以使用引號(hào)包裹的
var json = '{a:"Hello",b:"World"}';//這是一個(gè)JSON字符串,本質(zhì)是一個(gè)字符串
JSON和 JavaScript 對(duì)象互轉(zhuǎn)
要實(shí)現(xiàn)從JSON字符串轉(zhuǎn)換為JavaScript對(duì)象,使用JSON.parse()方法:
var obj = JSON.parse('{a:"Hello",b:"World"}');
//結(jié)果是 {a:'Hello',b:'World'}
要實(shí)現(xiàn)從JavaScript對(duì)象轉(zhuǎn)化為JSON字符串,使用JSON.stringify()方法:
var json = JSON.stringify({a:'Hello',b:'World'});
//結(jié)果是 '{a:"Hello",b:"World"}'
代碼測(cè)試
新建一個(gè)module,spring-05-json,添加web支持 在web目錄下新建一個(gè)jsontest.html,編寫(xiě)測(cè)試內(nèi)容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
//編寫(xiě)一個(gè)JavaScript對(duì)象
var user={
name:"張三",
age:3,
sex:"男"
};
console.log(user);
//將 js 對(duì)象轉(zhuǎn)換為 json 對(duì)象;
var json = JSON.stringify(user);
console.log(json);
//將 json 對(duì)象轉(zhuǎn)換為 js 對(duì)象;
var obj = JSON.parse(json);
console.log(obj);
</script>
</head>
<body>
</body>
</html>
在IDEA中使用瀏覽器打開(kāi),查看控制臺(tái)輸出。
Controller返回 JSON數(shù)據(jù)
- Jackson應(yīng)該是目前比較好的json解析工具了
- 當(dāng)然工具不止這一個(gè),比如還有阿里巴巴的 fastjson 等等。
- 我們這里使用 Jackson,使用它需要導(dǎo)入它的jar包。
Jackson
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</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"> <!--1.注冊(cè)servlet--> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--通過(guò)初始化參數(shù)指定SpringMVC配置文件的位置,進(jìn)行關(guān)聯(lián)--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- 啟動(dòng)順序,數(shù)字越小,啟動(dòng)越早 --> <load-on-startup>1</load-on-startup> </servlet> <!--所有請(qǐng)求都會(huì)被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.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--自動(dòng)掃描包,讓指定包下的注解生效,有IOC容器統(tǒng)一管理--> <context:component-scan base-package="com.kuang.controller"/> <!--讓springmvc 不處理靜態(tài)資源--> <mvc:default-servlet-handler/> <!--開(kāi)啟注解支持--> <mvc:annotation-driven/> <!--配置視圖解析器--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前綴解析器--> <property name="prefix" value="/WEB-INF/jsp/"></property> <!--后綴解析器--> <property name="suffix" value=".jsp"></property> </bean> </beans>
編寫(xiě)一個(gè)User實(shí)體類
//需要導(dǎo)入lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
編寫(xiě)一個(gè)測(cè)試類Controller
@Controller
public class UserController {
@RequestMapping("/json1")
@ResponseBody //他就不去走視圖解析器,直接返回一個(gè)字符串
public String json1() throws Exception{
//jackson
ObjectMapper mapper =new ObjectMapper();
User user = new User("張三01",21,"男");
String str = mapper.writeValueAsString(user);
return str;
}
}
配置Tomcat , 啟動(dòng)測(cè)試一下!
http://localhost:8080/json1

發(fā)現(xiàn)出現(xiàn)了亂碼問(wèn)題,我們需要設(shè)置一下他的編碼格式為utf-8,以及它返回的類型;
通過(guò)@RequestMapping的produces屬性來(lái)實(shí)現(xiàn),修改下代碼:
//沒(méi)有在配置文件中配置,可以單個(gè)解決亂碼 //produces:指定響應(yīng)體返回類型和編碼 @RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")
再次測(cè)試, http://localhost:8080/json1 , 亂碼問(wèn)題OK!

亂碼統(tǒng)一解決
上一種方法比較麻煩,如果項(xiàng)目中有許多請(qǐng)求則每一個(gè)都要添加,可以通過(guò)Spring配置統(tǒng)一指定,這樣就不用每次都去處理了!
我們可以在springmvc的配置文件上添加一段消息StringHttpMessageConverter轉(zhuǎn)換配置!
<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字符串統(tǒng)一解決
在類上直接使用 @RestController ,這樣子,里面所有的方法都只會(huì)返回 json 字符串了,不用再每一個(gè)都添加@ResponseBody !我們?cè)谇昂蠖朔蛛x開(kāi)發(fā)中,一般都使用 @RestController ,十分便捷!
@RestController
public class UserController {
//produces:指定響應(yīng)體返回類型和編碼
@RequestMapping(value = "/json1")
public String json1() throws JsonProcessingException {
//創(chuàng)建一個(gè)jackson的對(duì)象映射器,用來(lái)解析數(shù)據(jù)
ObjectMapper mapper = new ObjectMapper();
//創(chuàng)建一個(gè)對(duì)象
User user = new User("張三1號(hào)", 3, "男");
//將我們的對(duì)象解析成為json格式
String str = mapper.writeValueAsString(user);
//由于@ResponseBody注解,這里會(huì)將str轉(zhuǎn)成json格式返回;十分方便
return str;
}
}
啟動(dòng)tomcat測(cè)試,結(jié)果都正常輸出!
測(cè)試集合輸出
增加一個(gè)新的方法
@RequestMapping("/json2")
@ResponseBody //他就不去走視圖解析器,直接返回一個(gè)字符串
public String json2() throws Exception{
//jackson
ObjectMapper mapper =new ObjectMapper();
List<User> userList = new ArrayList<User>();
User user1 = new User("張三01",21,"男");
User user2 = new User("張三02",21,"男");
User user3 = new User("張三03",21,"男");
User user4 = new User("張三04",21,"男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
String str = mapper.writeValueAsString(userList);
return str;
}
運(yùn)行結(jié)果 : 沒(méi)有任何問(wèn)題!

輸出時(shí)間對(duì)象
增加一個(gè)新的方法
@RequestMapping("/json3")
public String json3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//創(chuàng)建時(shí)間一個(gè)對(duì)象,java.util.Date
Date date = new Date();
//將我們的對(duì)象解析成為json格式
String str = mapper.writeValueAsString(date);
return str;
}
運(yùn)行結(jié)果 :

- 默認(rèn)日期格式會(huì)變成一個(gè)數(shù)字,是1970年1月1日到當(dāng)前日期的毫秒數(shù)!
- Jackson 默認(rèn)是會(huì)把時(shí)間轉(zhuǎn)成timestamps形式
解決方案一:使用SimpleDateFormat,自定義時(shí)間格式
@RequestMapping("/json3")
@ResponseBody //他就不去走視圖解析器,直接返回一個(gè)字符串
public String json3() throws Exception {
//jackson
ObjectMapper mapper = new ObjectMapper();
Date date = new Date();
//自定義日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return mapper.writeValueAsString(sdf.format(date));
}
解決方案二:取消timestamps形式 , 自定義時(shí)間格式
@RequestMapping("/json4")
@ResponseBody //他就不去走視圖解析器,直接返回一個(gè)字符串
public String json4() throws Exception {
//jackson
ObjectMapper mapper = new ObjectMapper();
//不使用時(shí)間戳的方式、
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//自定義日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
mapper.setDateFormat(sdf);
Date date = new Date();
return mapper.writeValueAsString(date);
}
運(yùn)行結(jié)果 : 成功的輸出了時(shí)間!

抽取成工具類
如果要經(jīng)常使用的話,這樣是比較麻煩的,我們可以將這些代碼封裝到一個(gè)工具類中;我們?nèi)ゾ帉?xiě)下
public class JSONUtils {
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object,String dateFormat){
//jackson
ObjectMapper mapper = new ObjectMapper();
//不使用時(shí)間戳的方式
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;
}
}
此時(shí)的代碼更加簡(jiǎn)潔。
@RequestMapping("/json5")
@ResponseBody //他就不去走視圖解析器,直接返回一個(gè)字符串
public String json5() throws Exception {
Date date = new Date();
return JSONUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");
}
FastJson
fastjson.jar是阿里開(kāi)發(fā)的一款專門(mén)用于Java開(kāi)發(fā)的包, 可以方便的實(shí)現(xiàn)json對(duì)象與JavaBean對(duì)象的轉(zhuǎn)換,實(shí)現(xiàn)JavaBean對(duì)象與json字符串的轉(zhuǎn)換,實(shí)現(xiàn)json對(duì)象 與json字符串的轉(zhuǎn)換。實(shí)現(xiàn)json的轉(zhuǎn)換方法很多,最后的實(shí)現(xiàn)結(jié)果都是一樣的。
導(dǎo)入pom依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.20</version> </dependency>
- 【JSONObject代表json對(duì)象】
- JSONObject實(shí)現(xiàn)了Map接口,猜想JSONObject底層操作是由Map實(shí)現(xiàn)的。
- JSONObject對(duì)應(yīng) json對(duì)象,通過(guò)各種形式的get()方法可以獲取json對(duì)象中的數(shù)據(jù),也可利用諸如size(),isEmpty()等方法獲取"鍵: 值"對(duì)的個(gè)數(shù)和判斷是否為空。其本質(zhì)是通過(guò)實(shí)現(xiàn)Map接口并調(diào)用接口中的方法完成的。
- 【JSONArray代表json對(duì)象數(shù)組】
- 內(nèi)部是有List接口中的方法來(lái)完成操作的。
- 【JSON代表JSONObject和 JSONArray的轉(zhuǎn)化】
- JSON類源碼分析與使用。
- 仔細(xì)觀察這些方法,主要是實(shí)現(xiàn)json對(duì)象,json對(duì)象數(shù)組,javabean對(duì)象,json字符串之間的相互轉(zhuǎn)化。
代碼測(cè)試:
@RequestMapping("/json6")
@ResponseBody
public String json6() throws Exception {
List<User> userList = new ArrayList<User>();
User user1 = new User("張三01",21,"男");
User user2 = new User("張三02",21,"男");
User user3 = new User("張三03",21,"男");
User user4 = new User("張三04",21,"男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
System.out.println("****Java對(duì)象 轉(zhuǎn) JSON字符串****");
String str1 = JSON.toJSONString(userList);
System.out.println(str1);
String str2 = JSON.toJSONString(user1);
System.out.println(str2);
System.out.println("****JSON字符串 轉(zhuǎn) Java對(duì)象****");
User jp_user1 = JSON.parseObject(str2, User.class);
System.out.println(jp_user1);
System.out.println("****Java對(duì)象 轉(zhuǎn) JSON對(duì)象****");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println(jsonObject1.getString("name"));
System.out.println("****JSON對(duì)象 轉(zhuǎn) Java對(duì)象****");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println(to_java_user);
return "Hello";
}
到此這篇關(guān)于做java這么久了居然還不知道JSON的使用(一文帶你了解)的文章就介紹到這了,更多相關(guān)java中json使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java異步調(diào)用的4種實(shí)現(xiàn)方法
日常開(kāi)發(fā)中,會(huì)經(jīng)常遇到說(shuō),前臺(tái)調(diào)服務(wù),本文主要介紹了java異步調(diào)用的4種實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
SpringBoot開(kāi)發(fā)案例之配置Druid數(shù)據(jù)庫(kù)連接池的示例
本篇文章主要介紹了SpringBoot開(kāi)發(fā)案例之配置Druid數(shù)據(jù)庫(kù)連接池的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03
寶塔面板配置及部署javaweb教程(全網(wǎng)最全)
這篇文章主要介紹了寶塔面板配置及部署javaweb教程(全網(wǎng)最全),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
java 數(shù)據(jù)結(jié)構(gòu)之刪除鏈表中的元素實(shí)例代碼
這篇文章主要介紹了java 數(shù)據(jù)結(jié)構(gòu)之刪除鏈表中的元素實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-01-01
springboot遠(yuǎn)程執(zhí)行服務(wù)器指令
這篇文章主要介紹了springboot遠(yuǎn)程執(zhí)行服務(wù)器指令,本例是java遠(yuǎn)程連接到服務(wù)器,去抓取查詢kubesphere中的etcd日志,并返回,需要的朋友可以參考下2023-09-09
Mybatis原始執(zhí)行方式Executor代碼實(shí)例
這篇文章主要介紹了Mybatis原始執(zhí)行方式Executor代碼實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07

