做java這么久了居然還不知道JSON的使用(一文帶你了解)
在JavaScript語言中,一切都是對(duì)象。因此,任何JavaScript 支持的類型都可以通過JSON來表示,例如字符串、數(shù)字、對(duì)象、數(shù)組等。看看他的要求和語法格式:
對(duì)象表示為鍵值對(duì),數(shù)據(jù)由逗號(hào)分隔 花括號(hào)保存對(duì)象 方括號(hào)保存數(shù)組JSON鍵值對(duì)是用來保存JavaScript對(duì)象的一種方式,和JavaScript對(duì)象的寫法也大同小異,鍵/值對(duì)組合中的鍵名寫在前面并用雙引號(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'}’
代碼測試
新建一個(gè)module,spring-05-json,添加web支持 在web目錄下新建一個(gè)jsontest.html,編寫測試內(nèi)容
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title> <script type='text/javascript'> //編寫一個(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中使用瀏覽器打開,查看控制臺(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> <!--通過初始化參數(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/> <!--開啟注解支持--> <mvc:annotation-driven/> <!--配置視圖解析器--> <bean class='org.springframework.web.servlet.view.InternalResourceViewResolver'> <!--前綴解析器--> <property name='prefix' value='/WEB-INF/jsp/'></property> <!--后綴解析器--> <property name='suffix' value='.jsp'></property> </bean></beans>
編寫一個(gè)User實(shí)體類
//需要導(dǎo)入lombok@Data@AllArgsConstructor@NoArgsConstructorpublic class User { private String name; private int age; private String sex;}
編寫一個(gè)測試類Controller
@Controllerpublic 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)測試一下!
http://localhost:8080/json1
發(fā)現(xiàn)出現(xiàn)了亂碼問題,我們需要設(shè)置一下他的編碼格式為utf-8,以及它返回的類型;
通過@RequestMapping的produces屬性來實(shí)現(xiàn),修改下代碼:
//沒有在配置文件中配置,可以單個(gè)解決亂碼//produces:指定響應(yīng)體返回類型和編碼@RequestMapping(value = '/json1',produces = 'application/json;charset=utf-8')
再次測試, http://localhost:8080/json1 , 亂碼問題OK!
亂碼統(tǒng)一解決
上一種方法比較麻煩,如果項(xiàng)目中有許多請(qǐng)求則每一個(gè)都要添加,可以通過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開發(fā)中,一般都使用 @RestController ,十分便捷!
@RestControllerpublic class UserController { //produces:指定響應(yīng)體返回類型和編碼 @RequestMapping(value = '/json1') public String json1() throws JsonProcessingException { //創(chuàng)建一個(gè)jackson的對(duì)象映射器,用來解析數(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測試,結(jié)果都正常輸出!
測試集合輸出
增加一個(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é)果 : 沒有任何問題!
輸出時(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é)果 :
解決方案一:使用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)ゾ帉懴?/p>
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í)的代碼更加簡潔。
@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是阿里開發(fā)的一款專門用于Java開發(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ì)象,通過各種形式的get()方法可以獲取json對(duì)象中的數(shù)據(jù),也可利用諸如size(),isEmpty()等方法獲取'鍵: 值'對(duì)的個(gè)數(shù)和判斷是否為空。其本質(zhì)是通過實(shí)現(xiàn)Map接口并調(diào)用接口中的方法完成的。 【JSONArray代表json對(duì)象數(shù)組】 內(nèi)部是有List接口中的方法來完成操作的。 【JSON代表JSONObject和 JSONArray的轉(zhuǎn)化】 JSON類源碼分析與使用。 仔細(xì)觀察這些方法,主要是實(shí)現(xiàn)json對(duì)象,json對(duì)象數(shù)組,javabean對(duì)象,json字符串之間的相互轉(zhuǎn)化。
代碼測試:
@RequestMapping('/json6')@ResponseBodypublic 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)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Android打包篇:Android Studio將代碼打包成jar包教程2. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis3. SpringBoot+TestNG單元測試的實(shí)現(xiàn)4. Springboot 全局日期格式化處理的實(shí)現(xiàn)5. vue實(shí)現(xiàn)web在線聊天功能6. 解決Android Studio 格式化 Format代碼快捷鍵問題7. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題8. JavaScript實(shí)現(xiàn)頁面動(dòng)態(tài)驗(yàn)證碼的實(shí)現(xiàn)示例9. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼10. Java使用Tesseract-Ocr識(shí)別數(shù)字
