详细的可以参考 https://www.jianshu.com/p/b804874b7a69
下面我整理了一些常用操作
如果是使用的springboot,并且引用了spring-boot-starter-web依赖包,这个依赖包会默认引用jackson的依赖,也就是用了springmvc,就可以用jackson
没有的话这里介绍一下jackson需要的依赖
对,就是3个,3个各有用处,并且三个模块之间存在依赖
三个模块的 作用及 artifactId 如下:
jackson-core: 核心包
jackson-annotations : 注解包
jackson-databind : 数据绑定(依赖 core 和 annotations)
而 jackson-databind 依赖另外两个,所以单独引用时,只引用 jackson-databind 就可以使用了.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
序列化操作
常用的就是序列化成字符串 writeValueAsString(Object o)
ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
writeValue(File arg0, Object arg1)
把arg1转成json序列,并保存到arg0文件中。
writeValue(OutputStream arg0, Object arg1)
把arg1转成json序列,并保存到arg0输出流中。
writeValueAsBytes(Object arg0)
把arg0转成json序列,并把结果输出成字节数组。
writeValueAsString(Object arg0)
把arg0转成json序列,并把结果输出成字符串。
使用Demo
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("小民");
user.setEmail("xiaomin@sina.com");
user.setAge(20);
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));
ObjectMapper mapper = new ObjectMapper();
//User类转JSON
//输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
String json = mapper.writeValueAsString(user);
System.out.println(json);
//Java集合转JSON
//输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
List<User> users = new ArrayList<User>();
users.add(user);
String jsonlist = mapper.writeValueAsString(users);
System.out.println(jsonlist);
}
}
反序列化操作
ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化
demo如下
import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}";
/**
* ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
*/
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}
json数组字符串转List<Map>
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
String jsonString="""[{"id":1},{"id":2}]"""
ObjectMapper objectMapper = new ObjectMapper()
List<Map> test = objectMapper.readValue(jsonString,new TypeReference<List<Map>>() {})
test.each {println(it)}
结果:
[id:1]
[id:2]
Result: [[id:1], [id:2]]
那么让我们稍微看一下readValue里面的方法
所以我们可以直接调用里面的方法
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
String jsonString="""[{"id":1},{"id":2}]"""
ObjectMapper objectMapper = new ObjectMapper()
List<Map> test = objectMapper.readValue(jsonString,objectMapper.getTypeFactory().constructType(List.class))
test.each {println(it.get("id"))}
结果
1
2
Result: [[id:1], [id:2]]
JSON注解
Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。
@JsonIgnore
此注解用于属性上,作用是进行JSON操作时忽略该属性。
@JsonFormat
此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
。
@JsonProperty
此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")
。
关于日期格式的格式化,jackson提供了两种方法
单独格式化,序列化的时候自动转成这个格式
@JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”)
private Date updateTime;
指定时区
@JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”,timezone=“GMT+8”)
private Date updateTime;
统一格式化
在yml中进行配置
#时间戳统一转换
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
或者手动配置
ObjectMapper om = new ObjectMapper();
// 属性为Null的不进行序列化,只对pojo起作用,对map和list不起作用
om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// json进行换行缩进等操作
om.enable(SerializationFeature.INDENT_OUTPUT);
// json不进行换行缩进等操作 默认就是不进行操作,写了这行和没写的效果一样
om.disable(SerializationFeature.INDENT_OUTPUT);
// json是否允许属性名没有引号 ,默认是false
om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
//json是否允许属性名为单引号 ,默认是false
om.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 遇到未知属性是否抛出异常 ,默认是抛出异常的
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 当实体类没有setter方法时,序列化不报错,返回一个空对象
om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 所有的字母小写,下划线作为名字之间分隔符,例如 snake_case
om.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
// 所有名字(包括第一个字符)都以大写字母开头,后跟小写字母,没有分隔符,例如 UpperCamelCase
om.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
// 第一个单词以小写字母开头,后续每个单词都是大写字母开头,没有分隔符,例如 lowerCamelCase
om.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
// 所有的字母小写,没有分隔符,例如 lowercase
om.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
// “Lisp” 风格,采用小写字母、连字符作为分隔符,例如 “lower-case” 或 “first-name”
om.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);