JSON(JavaScript Object Notation,JS 对象标记)是一种轻量级的数据交换格式
采用完全独立于编程语言的文本格式来存储和表示数据
JSON 键值对是用来保存 JavaScript 对象的一种方式
比如:{"name": "张三"},前者键,后者值,冒号分隔
写个 HTML
script 写在 <head> 里
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> var user = { name:"张三", age:18, sex:"男" }; console.log(user); </script> </head> <body> </body> </html>
直接在 idea 里查看网页效果
可以看到控制台打印成功
js 和 json 可以互相转换
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> var user = { name:"张三", age:18, sex:"男" }; //将 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>
前者字符串,后者对象
Jackson 是 json 解析工具
pom.xml 文件导入 jackson 的 jar 包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.17.2</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" metadata-complete="true"> <!-- 注册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> <!-- 配置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>
resources 目录下创建 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:mvc="http://www.springframework.org/schema/mvc" 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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 --> <context:component-scan base-package="com.demo.controller"/> <!-- 让SpringMVC不处理静态资源 --> <mvc:default-servlet-handler/> <!-- 支持MVC注解驱动 --> <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>
pom.xml 文件导入 lombok 的 jar 包
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.34</version> <scope>provided</scope> </dependency>
写个 User 类,设置有参构造和无参构造的注解
package com.demo.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //需要导入lombox @Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
写个控制器
@ResponseBody 表示不走视图解析器,直接返回字符串
jackson 使用方法:
1. new 一个 ObjectMapper
2. 调用 writeValueAsString 方法,转换成 String 类型
方法1:可以使用 @RequestMapping 注解里的 produces 解决 json 乱码
produces = "application/json;charset=utf-8"
package com.demo.controller; import com.demo.pojo.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { //解决中文乱码 @RequestMapping(value = "/json",produces = "application/json;charset=utf-8") //@RequestMapping("/json") @ResponseBody //加了@ResponseBody表示不走视图解析器,返回字符串 public String json() throws JsonProcessingException { //jackson ObjectMapper mapper = new ObjectMapper(); //创建一个对象 User user = new User("张三",18,"男"); String value = mapper.writeValueAsString(user); //return user.toString(); return value; } }
json 请求时出现乱码,SpringMVC 提供了统一解决乱码的方式
方法2:springmvc-servlet.xml 文件添加 json 解决乱码配置
<!-- JSON乱码问题配置 --> <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 就把这段加上
运行,中文可以正常显示
如果设置了 @RestController 注解,表示只返回 json 形式
package com.demo.controller; import com.demo.pojo.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class UserController { @RequestMapping("/json2") public String json2() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); List<User> userList = new ArrayList<User>(); User user1 = new User("张三1",18,"男"); User user2 = new User("张三2",18,"男"); User user3 = new User("张三3",18,"男"); userList.add(user1); userList.add(user2); userList.add(user3); String value = mapper.writeValueAsString(userList); return value; } }
中括号表示这是一个 list 集合
大括号表示它是一个具体的对象
获取时间:
package com.demo.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.SimpleDateFormat; import java.util.Date; @RestController public class UserController { @RequestMapping("/json3") public String json3() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); Date date = new Date(); //自定义日期格式 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //ObjectMapper,时间解析后的默认格式为:Timestamp时间戳 return mapper.writeValueAsString(simpleDateFormat.format(date)); } }
FastJson 可以实现 json 对象与 JavaBean 对象的转换
实现 JavaBean 对象与 json 字符串的转换
实现 json 对象与 json 字符串的转换
导入 fastjson 的 jar 包
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.51</version> </dependency>
直接使用 JSON.toJSONString 即可
package com.demo.controller; import com.alibaba.fastjson.JSON; import com.demo.pojo.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class UserController { @RequestMapping("/json4") public String json4() throws JsonProcessingException { List<User> userList = new ArrayList<User>(); User user1 = new User("张三1",18,"男"); User user2 = new User("张三2",18,"男"); User user3 = new User("张三3",18,"男"); userList.add(user1); userList.add(user2); userList.add(user3); String value = JSON.toJSONString(userList); return value; } }
Java 对象转 JSON 字符串:JSON.toJSONString()
JSON 字符串转 Java 对象:JSON.parseObject()
Java 对象转 JSON 对象:JSON.toJSON()
JSON 对象转 Java 对象:JSON.toJavaObject()