JSON(JavaScript Object Notation,JS對象標記)是一種輕量級的數據交換格式,目前使用特別普遍。javascript
採用徹底獨立於編程語言的文本格式來存儲和表示數據。html
簡潔和清晰的層級結構使得JSON成爲理想的數據交換格式。java
易於人閱讀和編寫,同時也易於機器解析和生成,並有效地提高網絡傳輸效率。web
在JavaScript語言中,一切都是對象。所以,任何JavaScript支持的類型均可以經過JSON來表示,例如字符串、數字、對象、數組等。spring
JSON的要求和語法格式:編程
JSON字符串---->JavaScript對象json
使用JSON.parse()方法數組
var obj = JSON.parse('{"a": "Hello", "b": "World"}'); //結果爲 {a: "Hello", b: "World"}
JavaScript對象---->JSON字符串網絡
使用JSON.stringify()方法mvc
car json = JSON.stringify({a: "Hello", b: "World"}); //結果爲 '{"a": "Hello", "b": "World"}'
在web頁面下新建一個json-1.html頁面
var user = { name: "張三", age: 5, sex: "男" }; var json = JSON.stringify(user); console.log(json) var obj = JSON.parse(json); console.log(obj)
使用IDEA打開,查看控制檯輸出!
Jackson是比較好的json解析工具
咱們這裏使用Jackson,須要導入它的jar包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency>
package com.star.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.star.pojo.User; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController //使用這個註解不經過視圖解析器,直接返回方法對應的類型 public class UserController { @RequestMapping("/j1") //這裏返回一個字符串 public String json() throws JsonProcessingException { //建立一個User對象 User user = new User("張三", 10, "男"); //建立一個jackson的對象映射器,用來解析數據 ObjectMapper mapper = new ObjectMapper(); //將咱們的對象解析爲json格式 String string = mapper.writeValueAsString(user); return string; } }
啓動測試!
發現有亂碼問題,咱們可使用兩種方法解決:
修改@RequestMapping註解
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
這種方式比較麻煩,若是項目中有許多的請求則每個一個都要添加,能夠經過配置文件統一隻當。
<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>
@RequestMapping("/j2") public String json2() throws JsonProcessingException { User user1 = new User("張三1號", 10, "男"); User user2 = new User("張三2號", 10, "男"); User user3 = new User("張三3號", 10, "男"); User user4 = new User("張三4號", 10, "男"); ArrayList<User> users = new ArrayList<User>(); users.add(user1); users.add(user2); users.add(user3); users.add(user4); ObjectMapper mapper = new ObjectMapper(); String string = mapper.writeValueAsString(users); return string; }
啓動測試:
@RequestMapping("/j3") public String json3() throws JsonProcessingException { Date date = new Date(); ObjectMapper mapper = new ObjectMapper(); String string = mapper.writeValueAsString(date); return string; }
啓動測試:
這裏默認日期格式會變成一個數字即從1970.1.1到如今的毫秒數!
咱們能夠將日期轉換爲咱們想要的格式,有兩種方法!
@RequestMapping("/j3") public String json3() throws JsonProcessingException { Date date = new Date(); //使用SimpleDateFormat類設置格式,調用format方法將時間轉爲該格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(date); ObjectMapper mapper = new ObjectMapper(); String string = mapper.writeValueAsString(format); return string; }
啓動測試:
顯示成功!
Jackson 默認是會把時間轉成timestamps形式,咱們能夠在代碼中取消默認的格式
@RequestMapping("/j3") public String json3() throws JsonProcessingException { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ObjectMapper mapper = new ObjectMapper(); //取消默認的時間格式 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //定義時間格式爲自定義的 mapper.setDateFormat(sdf); //將時間對象轉爲JSON字符串 String string = mapper.writeValueAsString(date); return string; }
啓動測試:
顯示成功!
這兩種方法均可以,能夠本身選擇!
若是要常常使用的話,這樣是比較麻煩的,咱們能夠將這些代碼封裝到一個工具類中
package com.star.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.text.SimpleDateFormat; import java.util.Date; 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){ ObjectMapper mapper = new ObjectMapper(); //取消默認的時間格式 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; } }
如今咱們使用工具類,代碼就更簡潔了!
@RequestMapping("/j4") public String json4() throws JsonProcessingException { Date date = new Date(); return JsonUtils.getJson(date); }
咱們也能夠修改集合的方法
@RequestMapping("/j2") public String json2() throws JsonProcessingException { User user1 = new User("張三1號", 10, "男"); User user2 = new User("張三2號", 10, "男"); User user3 = new User("張三3號", 10, "男"); User user4 = new User("張三4號", 10, "男"); ArrayList<User> users = new ArrayList<User>(); users.add(user1); users.add(user2); users.add(user3); users.add(user4); return JsonUtils.getJson(users) }
fastjson.jar是阿里開發的一款專門用於Java開發的包,能夠方便的實現json對象與JavaBean對象的轉換,實現JavaBean對象與json字符串的轉換,實現json對象與json字符串的轉換。實現json的轉換方法不少,最後的實現結果都是同樣的。
導入依賴:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency>
FastJson三個主要的類:
JSONObject表明json獨對象
JSONArray 表明json對象數組
JSON表明JSONObject和JSONArray的轉換
@RequestMapping("/fj1") public String json(){ User user1 = new User("張三1號", 10, "男"); User user2 = new User("張三2號", 10, "男"); User user3 = new User("張三3號", 10, "男"); User user4 = new User("張三4號", 10, "男"); ArrayList<User> users = new ArrayList<User>(); users.add(user1); users.add(user2); users.add(user3); users.add(user4); String string = JSON.toJSONString(users); return string; }
啓動測試:
經常使用的轉換:
Java對象 ===> JSON字符串
JSON.toJSONString(object)
JSON字符串 ===> Java對象
JSON.paresObject(json, object.class)
Java對象 ===> JSON對象
(JSONObject) JSON.toJSON(object)
JSON對象 ===> Java對象
JSON.toJavaObject(jsonObject, object.class)
這種工具類,咱們只須要掌握使用就行了,在使用的時候在根據具體的業務去找對應的實現。拿來用就行了!