Jackson学习笔记
1、去官网下载Jackson工具包,
下载地址:https://mvnrepository.com/artifact/com.fasterxml.jackson
Jackson有1.x系列和2.x系列,截止目前2.x系列的最新版本是2.2.3,2.x系列有3个jar包需要下载:
jackson-core-2.2.3.jar(核心jar包)
jackson-annotations-2.2.3.jar(该包提供Json注解支持)
jackson-databind-2.2.3.jar
IDEA中使用maven中导入依赖
1、Jackson Core
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.3</version>
</dependency>
2、jackson-annotations
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.3</version>
</dependency>
3、jackson-databind
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
json轻量级的数据转化
JSON对象和JavaScript对象的转化
- 将JavaScript对象转化为json对象使用【JSON.stringify()】
-将json对象转化为JavaScript对象使用【JSON.parse()】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript">
//编写javascript对象
var student = {
name: "小李",
age: 18,
sex: "男"
}
//将JavaScript对象转化为json对象
var json = JSON.stringify(student);
console.log(json);
console.log("-------------------");
//将json对象转化为JavaScript对象
var obj = JSON.parse(json);
console.log(obj);
</script>
</body>
</html>
结果
二、在springMVC中使用json转化数据
1、在pom.xml中导入json依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
2、web.xml文件的编写(servlet以及filter编写位置)
<?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">
<!--配置DispatchServlet;这个是springMVC的核心,请求分发器,前端控制器-->
<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>
<!--在springMVC中,/:代表匹配所有的请求,不包括jsp页面。/*:匹配所有的请求,包括jsp-->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
resource 资源下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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让指定包下的注解生效,有ioc容器统一管理-->
<context:component-scan base-package="com.zheng.controller"/>
<!--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="true"/>
</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>
实体类
package com.zheng.pojo;
public class Student {
private String name;
private int age;
private String sex;
public Student() {
}
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
工具类
package com.zheng.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) {
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;
}
}
控制层
package com.zheng.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.zheng.pojo.Student;
import com.zheng.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;
//@RestController 可以不用写@ResponseBody 。@ResponseBody 需要和@Controller 配合使用
@Controller
public class StudentController {
@RequestMapping("/j1")
@ResponseBody //不会走视图解析器,直接返回字符串 //测试对象转化为json
public String json() throws JsonProcessingException {
//json
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
Student student = new Student("小红", 18, "女");
//对象转化为json字符串
String str = mapper.writeValueAsString(student);
return str;
}
@RequestMapping("/j2")
@ResponseBody //测试集合对象转化为json
public String json1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//创建集合
List<Student> studentList = new ArrayList<Student>();
Student student1 = new Student("小红", 18, "女");
Student student2= new Student("小明", 18, "女");
Student student3 = new Student("小青", 18, "女");
Student student4 = new Student("小紫", 18, "女");
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
String str = mapper.writeValueAsString(studentList);
return str;
}
@RequestMapping("j3")
@ResponseBody //测试当前时间用代码的形式
public String json2() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM--dd HH:mm:ss");
return mapper.writeValueAsString( sdf.format(date));
}
@RequestMapping("j4")
@ResponseBody //测试当前时间用代码的形式
public String json3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM--dd HH:mm:ss");
mapper.setDateFormat(sdf);
Date date = new Date();
return mapper.writeValueAsString(date);
}
@RequestMapping("j5")
@ResponseBody //测试当前时间用代码的形式
public String json4() throws JsonProcessingException {
Date date = new Date();
return JsonUtils.getJson(date,"yyyy-MM--dd HH:mm:ss");
}
@RequestMapping("j6")
@ResponseBody //测试当前时间用代码的形式
public String json5() throws JsonProcessingException {
Date date = new Date();
return JsonUtils.getJson(date);
}
}