Json
概念
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。
易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。
定义
-
数据为 键/值 对。
-
数据由逗号分隔。
-
大括号保存对象
-
方括号保存数组
-
键/值对包括字段名称(在双引号中),后面一个冒号,然后是值
'{"name":"www","age":"10"}';//JSON {name:"www",age:10};//js对象
转化
var Person = {
name:'www',
age:10,
hobbies:['play', 'code', 'eat']
}
var json = JSON.stringify(Person);//将对象转化为JSON字符串
console.log(json);
>"{"name":"www","age":10,"hobbies":["play","code","eat"]}"
var obj = JSON.parse(json);//将JSON字符串转化为对象
console.log(obj);
>Object { name: "www", age: 10, hobbies: (3) […] }
返回json格式
-
导入Jackson的jar包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.4</version> </dependency>
-
配置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"> <!--DispatcherServlet--> <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> <!-- 配置springMVC乱码过滤--> <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>
将Json字符串显示到页面
json.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> // 定义js对象 var user = { name:"www", age:20 } console.log(user); // 将js对象转化为json var json = JSON.stringify(user); console.log(json); // 将json转化为js var obj = JSON.parse(json); console.log(obj); </script> </head> <body> </body> </html>
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> <!-- 配置springMVC乱码过滤 请求给服务器时产生的乱码--> <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-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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="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 http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <context:component-scan base-package="com.wjq.controller"/> <!-- 此配置可以不用写--> <mvc:default-servlet-handler/> <mvc:annotation-driven> <!-- springmvc处理乱码 由服务器返回显示在页面上的乱码--> <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> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
controller【测试返回】
package com.wjq.controller; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.wjq.pojo.User; import com.wjq.utils.TimeUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller//会走视图解析器,和@ResponseBody配合使用 //@RestController直接返回字符串,不走视图解析器 public class UserController { //正常情况下会将结果返回给视图解析器,而json需要返回字符串,可以通过Jackson的jar包来完成 @RequestMapping("/json1")//会有乱码现象 @ResponseBody//服务器将返回的对象转换为json字符串形式,不走视图解析器,直接返回字符串 public String testJson1() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(1, "大头", 20); System.out.println(user); String string = mapper.writeValueAsString(user); return string;//由于使用了@ResponseBody这里将以json字符串的形式返回 } @RequestMapping(value = "/json2", produces = "application/json;charset=utf-8")//produces用来解决乱码的问题 @ResponseBody//服务器将返回的对象转换为json字符串形式 public String testJson2() throws JsonProcessingException { User user = new User(1, "大头", 20); return new ObjectMapper().writeValueAsString(user);//由于使用了@ResponseBody这里将以json字符串的形式返回 } @RequestMapping("/json3")//用配置文件来解决乱码的问题 @ResponseBody//服务器将返回的对象转换为json字符串形式 public String testJson3() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(1, "大头", 20); System.out.println(user); String string = mapper.writeValueAsString(user); return string;//由于使用了@ResponseBody这里将以json字符串的形式返回 } @RequestMapping(value = "/json4")//用配置文件来解决乱码的问题 @ResponseBody//服务器将返回的对象转换为json字符串形式 public String testJson4() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); List<User> list = new ArrayList<User>(); User user1 = new User(1, "大头1", 20); User user2 = new User(2, "大头2", 20); list.add(user1); list.add(user2); return mapper.writeValueAsString(list);//由于使用了@ResponseBody这里将以json字符串的形式返回 } @RequestMapping(value = "/time1")//用配置文件来解决乱码的问题 @ResponseBody//服务器将返回的对象转换为json字符串形式 public String testJson5() throws JsonProcessingException { Date date = new Date(); System.out.println(date);//返回格林..时间 return new ObjectMapper().writeValueAsString(date);//返回时间戳 //由于使用了@ResponseBody这里将以json字符串的形式返回 } @RequestMapping(value = "/time2")//用配置文件来解决乱码的问题 @ResponseBody//服务器将返回的对象转换为json字符串形式 public String testJson6() throws JsonProcessingException { //如何不返回时间戳,关闭时间戳的功能 ObjectMapper mapper = new ObjectMapper(); //关闭时间戳功能 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //设置指定时间格式 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); //让mapper的日期格式指定为 mapper.setDateFormat(dateFormat); Date date = new Date(); return mapper.writeValueAsString(date);//返回指定的时间格式 //由于使用了@ResponseBody这里将以json字符串的形式返回 } @RequestMapping(value = "/time3")//用配置文件来解决乱码的问题 @ResponseBody//服务器将返回的对象转换为json字符串形式 public String testJson7() throws JsonProcessingException { return TimeUtil.timeFormat(new Date()); //由于使用了@ResponseBody这里将以json字符串的形式返回 } //使用FastJson @RequestMapping(value = "/FJ1")//用配置文件来解决乱码的问题 @ResponseBody//服务器将返回的对象转换为json字符串形式 public String testJson8() throws JsonProcessingException { List<User> list = new ArrayList<User>(); User user1 = new User(1, "大头1", 20); User user2 = new User(2, "大头2", 20); list.add(user1); list.add(user2); System.out.println(JSON.toJSONString(list)); return "111";//由于使用了@ResponseBody这里将以json字符串的形式返回 } //视图解析器分为两种: // 基于url的:例如InternalResourceViewResolver,将解析(返回)的结果拼接到url中 // 其他类型的:比如writeValueAsString将解析(返回)的结果以json的格式返回 }
TimeUtils
package com.wjq.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; /** * @author wjq * @create 2021-03-06 20:42 */ public class TimeUtil { public static String timeFormat(Object object, String format) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); SimpleDateFormat sdf = new SimpleDateFormat(format); mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); return "exception"; } } //重载自己设置的时间 public static String timeFormat(Object object) throws JsonProcessingException { return timeFormat(object, "yyyy:MM:dd HH:mm:ss"); } }
依赖
<dependencies> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.61</version> </dependency> </dependencies>
FastJson
fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json和JavaBean之间的转换。