Jackson和Fastjson使用


Jackson应该是目前比较好的json解析工具了

当然工具不止这一个,比如还有阿里巴巴的fastjson等等

我们这里使用jackson,使用它需要导入它的jar包


com.fasterxml.jackson.core
jackson-databind
2.10.0

配置SpringMVC,

web.xml

<?xml version="1.0" encoding="UTF-8"?>
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">

springmvc
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
classpath:springmvc-servlet.xml




springmvc
/



encoding
org.springframework.web.filter.CharacterEncodingFilter

encoding
utf-8



encoding
/*


springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
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">












再随便编写一个User实体类,然后去编写测试Controller

 controller:(@ResponseBody配合@Controller使用,可直接使用@RestController,其下的方法都不走视图解析器)

 测试:

 接下来改动一下controller,使用ObjectMapper对象

 测试:

 发现出现乱码问题,需要设置一下编码格式为utf-8,以及返回类型

1.可以通过@RequestMapping的produces属性实现,修改代码:

 测试:

2.乱码统一解决,可以通过Spring配置统一制定,在SpringMVC的配置文件(springmvc-servl.xml)上添加一段消息StringHttpMessageConverter转换配置














 测试:

 我们再编写一个集合测试:

 测试:

 我们再来一个时间对象

 测试:

 1970年1月1日到当前日期的毫秒数

jackson默认把时间转换成timestamps形式

我们通过一些方法将其转换成我们看的懂的时间:

1.Java方法:

 测试:

 2.ObjectMapper格式化输出,不使用时间戳方式

我们编写一个工具类封装代码:

 那么我们的controller代码:

 ================

Fastjson

导包


com.alibaba
fastjson
1.2.60