💗wei_shuo的个人主页
💫wei_shuo的学习社区
🌐Hello World !
JSON
JSON(
JavaScript
Object Notation,JS对象简谱)是一种轻量级的数据交换格式。它基于ECMAScript
(European Computer Manufacturers Association,欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率
特点:
- 对象表示键值对,数据由逗号分隔
- 花括号保存对象{}
- 方括号保存数据[]
语法格式:
{"name":"wei_shuo"} {"age":"3"} {"sex":"男"}
JSON & JavaScript对象相互转换
JavaScript对象 ——> JSON对象
<script type="text/javascript">//编写一个JavaScript对象var user = {name: "wei_shuo",age: 18,sex: "男"};//将JavaScript对象转换为JSON对象let json = JSON.stringify(user);console.log(json);</script>
JSON对象 ——> JavaScript对象
<script type="text/javascript">//编写一个JavaScript对象var user = {name: "wei_shuo",age: 18,sex: "男"};//将JSON对象对象转换为JavaScript对象let obj = JSON.parse(json);console.log(obj)</script>
var、let、const | 全局、函数、块级作用域
函数作用域:var
块级作用域:let、const
全局作用域:函数之外,使用var进行定义,在全局中都能使用的变量,称为
全局变量
,全局变量对应的作用域就是全局作用域
函数作用域:函数之内,使用var进行定义,只能在该函数中使用的变量,称为
函数变量
(局部变量),局部变量对应的作用域就是函数作用域
(局部作用域)块级作用域:ES6中,可以通过关键词let来定义变量,通过let定义的变量,只能在当前代码块(以 { } 为界限)中使用,对应的作用域为
块级作用域
Jackson
Jackson 是用来解析 JSON 的框架是一种数据格式,用来在客户端和服务器之间,或系统组件之间交换数据
环境搭建
- pom.xml中导包:导入Jackson和lambok的jar包
<dependencies><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.14.0-rc3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency> </dependencies>
- 配置核心配置文件: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><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><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-servlet.xml映射文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 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"><!--自动扫描指定的包,下面所有的注解交给IOC容器管理--><context:component-scan base-package="com.wei.controller"/><!--配置annotation-driven使:处理器映射器 和 处理器适配器 自动完成实例的注入--><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>
- User类
@Data @AllArgsConstructor @NoArgsConstructor public class User {private String name;private int age;private String sex; }
- UserController类
@Controller public class UserController {//produces = "application/json;charset=utf-8" : 解决JSON对象乱码问题@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")@ResponseBody //@ResponseBody不会通过视图解析器,会直接返回一个字符串public String json1() throws JsonProcessingException {//使用jackson包,创建ObjectMapper对象ObjectMapper mapper = new ObjectMapper();//创建对象User user = new User("wei_shuo",18,"男");String str = mapper.writeValueAsString(user);return str;} }
JSON乱码解决
注解方式
//produces = "application/json;charset=utf-8" : 解决JSON对象乱码问题@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
Spring配置方式
<!--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对象
- @Controller:代码通过视图解析器
- @RequestMapping:处理请求地址映射
- @ResponseBody:@ResponseBody不会通过视图解析器,会直接返回一个字符串,同@Controller注解同时使用
- @RestController:直接返回一个字符串
- JSON返回普通对象
//代码通过视图解析器 @Controller public class UserController {//produces = "application/json;charset=utf-8" : 解决JSON对象乱码问题@RequestMapping(value = "/j1")@ResponseBody //@ResponseBody不会通过视图解析器,会直接返回一个字符串public String json1() throws JsonProcessingException {//使用jackson包,创建ObjectMapper对象ObjectMapper mapper = new ObjectMapper();//创建对象User user = new User("wei_shuo",18,"男");String str = mapper.writeValueAsString(user);return str;} }
- JSON返回集合对象
//直接返回一个字符串 @RestController public class UserController {@RequestMapping("/j2")public String json2() throws JsonProcessingException {//使用jackson包,创建ObjectMapper对象ObjectMapper mapper = new ObjectMapper();//创建集合对象ArrayList<User> userList = new ArrayList<>();//创建对象User user1 = new User("wei_shuo",18,"男");User user2 = new User("tian_tain",19,"男");User user3 = new User("wu_wu",14,"男");User user4 = new User("qi_qi",25,"男");userList.add(user1);userList.add(user2);userList.add(user3);userList.add(user4);String str = mapper.writeValueAsString(userList);return str;} }
- JSON返回时间对象
@RestController public class UserController {@RequestMapping("/j3")public String json3() throws JsonProcessingException {//使用jackson包,创建ObjectMapper对象ObjectMapper mapper = new ObjectMapper();//创建时间对象Date date = new Date();//自定义日期格式SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String format = sdf.format(date);String str = mapper.writeValueAsString(format);return str; // "2022-11-19 18:08:43"} }
- 编写utils工具类返回时间对象(JsonUtils类)
package com.wei.utils;import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature;import java.text.SimpleDateFormat;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对象ObjectMapper mapper = new ObjectMapper();//不使用时间戳的方式mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);//自定义日期的格式SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);mapper.setDateFormat(sdf);try {return mapper.writeValueAsString(object);} catch (JsonProcessingException e) {e.printStackTrace();}return null;} }
- UserController类
//直接返回一个字符串 @RestController public class UserController {@RequestMapping("/j1")public String json2() throws JsonProcessingException {//创建集合对象ArrayList<User> userList = new ArrayList<>();//创建对象User user1 = new User("wei_shuo",18,"男");User user2 = new User("tian_tain",19,"男");User user3 = new User("wu_wu",14,"男");User user4 = new User("qi_qi",25,"男");userList.add(user1);userList.add(user2);userList.add(user3);userList.add(user4);return JsonUtils.getJson(userList);}@RequestMapping("/j2")public String json3() throws JsonProcessingException {//创建时间对象Date date = new Date();return JsonUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");} }
FastJson
Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端等多种应用场景
环境搭建
- 导入pom.xml依赖
<dependencies><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.18</version></dependency> </dependencies>
- 使用FastJson
@RestController public class UserController {@RequestMapping("/j1")public String json1() throws JsonProcessingException {//创建集合对象ArrayList<User> userList = new ArrayList<>();//创建对象User user1 = new User("wei_shuo",18,"男");User user2 = new User("tian_tain",19,"男");User user3 = new User("wu_wu",14,"男");User user4 = new User("qi_qi",25,"男");userList.add(user1);userList.add(user2);userList.add(user3);userList.add(user4);String s = JSON.toJSONString(userList);return s;} }
Java <——> Json相互转换
Java对象——>Json字符串 | JSON.toJSONString(Object,object); |
---|---|
Json字符串——>Java对象 | JSON.parseObject(String str, Class objectClass); |
Java对象——>Json对象 | JSON.parseObject(String str, Class objectClass); |
Java对象——>Json对象 | JSON.toJSON(Object javaObject); |
Json对象——>Java对象 | JSON.toJavaObject(JSON json, Class clazz); |
@RestController
public class UserController {@RequestMapping("/j1")public String json1() throws JsonProcessingException {//创建集合对象ArrayList<User> userList = new ArrayList<>();//创建对象User user1 = new User("wei_shuo", 18, "男");User user2 = new User("tian_tain", 19, "男");User user3 = new User("wu_wu", 14, "男");User user4 = new User("qi_qi", 25, "男");userList.add(user1);userList.add(user2);userList.add(user3);userList.add(user4);System.out.println("Java对象——>Json字符串");String str1 = JSON.toJSONString(userList);System.out.println("JSON字符串:" + str1);System.out.println("=================");String str2 = JSON.toJSONString(user1);System.out.println("JSON字符串:" + str2);System.out.println("=================");System.out.println("Json字符串——>Java对象");User Json_TO_Java1 = JSON.parseObject(str2, User.class);System.out.println("Java对象:" + Json_TO_Java1);System.out.println("Java对象——>Json对象");JSONObject jsonObject = (JSONObject) JSON.toJSON(user1);System.out.println("Json对象:" + jsonObject.getString("name"));System.out.println("Json对象——>Java对象");User Json_TO_Java2 = JSON.toJavaObject(jsonObject, User.class);System.out.println("Java对象:" + Json_TO_Java2);return "Hello";}
}/*
输出结果:
Java对象——>Json字符串
JSON字符串:[{"age":18,"name":"wei_shuo","sex":"男"},{"age":19,"name":"tian_tain","sex":"男"},{"age":14,"name":"wu_wu","sex":"男"},{"age":25,"name":"qi_qi","sex":"男"}]
=================
JSON字符串:{"age":18,"name":"wei_shuo","sex":"男"}
=================
Json字符串——>Java对象
Java对象:User(name=wei_shuo, age=18, sex=男)
Java对象——>Json对象
Json对象:wei_shuo
Json对象——>Java对象
Java对象:User(name=wei_shuo, age=18, sex=男)
*/
🌼 结语:创作不易,如果觉得博主的文章赏心悦目,还请——
点赞
👍收藏
⭐️评论
📝