Jackson 详解
使用Jackson
1. pom.xml文件中引入依赖
1
<dependency>
2
<groupId>com.fasterxml.jackson.core</groupId>
3
<artifactId>jackson-databind</artifactId>
4
<version>2.9.5</version>
5
</dependency>
一般情况下,SpringBoot开发web应用会引用 spring-boot-start-web 依赖,而这个依赖会默认引用
Jackson 由三部分组成:
jackson-core
:核心包jackson-annotationas
:注解包jackson-databind
:数据绑定(依赖core
和annotations
)
jackson-databind
依赖另外两个,顾单独引用时,只需引用jackson-databind
即可
2. 使用
Jackson最常用的 API 就是基于“对象绑定”的ObjectMapper
。下面是ObjectMapper
的使用示例:
x
1
public class Test {
2
public static void main(String[] args) throws IOException {
3
ObjectMapper mapper = new ObjectMapper();
4
Person person = new Person();
5
person.setUsername("Tom");
6
person.setAge(25);
7
8
// 对象序列化
9
// writerWithDefaultPrettyPrinter() 打印美化
10
String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person);
11
System.out.println("对象序列化:
" + jsonStr);
12
// 对象反序列化
13
Person deserializedPerson = mapper.readValue(jsonStr, Person.class);
14
System.out.println("对象反序列化:
" + deserializedPerson);
15
}
16
}
输出:
1
对象序列化:
2
{"username":"Tom","age":25}
3
对象反序列化:
4
Person{username='Tom', age=25}
5
6
Process finished with exit code 0
ObjectMapper
通过writeValue
系列方法将 java 对象序列化为 json,并将 json 存储成不同格式。
String(writeValueAsString)
,Byte Array(writeValueAsString)
,Writer
,File
,OutStream
和DataOutput
。
ObjectMapper
通过readValue
系列方法从不同的数据源像String
,Byte Array
,Reader
,File
,URL
,InputStream
将 json 反序列化为 java 对象。
3. 信息配置
在调用 writeValue
或调用 readValue
方法之前,往往需要设置 ObjectMapper 的相关配置信息。这些配置信息应用 java 对象的所有属性上:
1
// 在反序列化时忽略在 json 中存在但 Java 对象不存在的属性
2
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
3
// 在序列化时日期格式默认为 yyyy-MM-dd'T'HH:mm:ss.SSSZ
4
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false)
5
// 在序列化时忽略值为 null 的属性
6
mapper.setSerializationInclusion(Include.NON_NULL);
7
// 忽略值为默认值的属性
8
mapper.setDefaultPropertyInclusion(Include.NON_DEFAULT);
9
...
4. jackson 注解的使用
Jackson 根据他的默认方式序列化和反序列化 java 对象。根据需要可灵活调整它的默认方式,可以使用Jackson注解。常用注解如下:
注解 | 用法 |
---|---|
@JsonProperty | 用于属性,把属性的名称序列化时转换为另外一个名称。示例: @JsonProperty("birth_ d ate") private Date birthDate; |
@JsonFormat | 用于属性或者方法,把属性的格式序列化时转换成指定的格式。示例: @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm") public Date getBirthDate() |
@JsonPropertyOrder | 用于类, 指定属性在序列化时 json 中的顺序 , 示例: @JsonPropertyOrder({ "birth_Date", "name" }) public class Person |
@JsonCreator | 用于构造方法,和 @JsonProperty 配合使用,适用有参数的构造方法。 示例: @JsonCreator public Person(@JsonProperty("name")String name) {…} |
@JsonAnySetter | 用于属性或者方法,设置未反序列化的属性名和值作为键值存储到 map 中 @JsonAnySetter public void set(String key, Object value) { map.put(key, value); } |
@JsonAnyGetter | 用于方法 ,获取所有未序列化的属性 public Map<String, Object> any() { return map; } |
5. 从 Reader 读取对象
xxxxxxxxxx
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
String carJson =
4
"{ "brand" : "Mercedes", "doors" : 4 }";
5
Reader reader = new StringReader(carJson);
6
7
Car car = objectMapper.readValue(reader, Car.class);
6. 从 File 中读取对象
xxxxxxxxxx
1
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
File file = new File("data/car.json");
4
5
Car car = objectMapper.readValue(file, Car.class);
7. 从 url 中读取对象
xxxxxxxxxx
1
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
URL url = new URL("file:data/car.json");
4
5
Car car = objectMapper.readValue(url, Car.class);
8. 从 InputStream 读取对象
xxxxxxxxxx
1
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
InputStream input = new FileInputStream("data/car.json");
4
5
Car car = objectMapper.readValue(input, Car.class);
9. 从字节数组中读取对象
xxxxxxxxxx
1
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
String carJson =
4
"{ "brand" : "Mercedes", "doors" : 5 }";
5
6
byte[] bytes = carJson.getBytes("UTF-8");
7
8
Car car = objectMapper.readValue(bytes, Car.class);
10. 从 Json 数组字符串中读取对象数组
xxxxxxxxxx
1
1
String jsonArray = "[{"brand":"ford"}, {"brand":"Fiat"}]";
2
3
ObjectMapper objectMapper = new ObjectMapper();
4
5
Car[] cars2 = objectMapper.readValue(jsonArray, Car[].class);
11. 从 Json 数组字符串中读取对象列表
xxxxxxxxxx
1
1
String jsonArray =“[{”brand “:”ford “},{”brand “:”Fiat “}]”;
2
3
ObjectMapper objectMapper = new ObjectMapper();
4
5
List <Car> cars1 = objectMapper.readValue(jsonArray,new TypeReference <List <Car >>(){});
12. 从 json 字符串中读取映射为 map
xxxxxxxxxx
1
1
String jsonObject =“{”brand “:”ford “,”doors “:5}”;
2
3
ObjectMapper objectMapper = new ObjectMapper();
4
Map <String,Object> jsonMap = objectMapper.readValue(jsonObject,
5
new TypeReference <Map <String,Object >>(){});
13. 树模型
x
1
String carJson =
2
"{ "brand" : "Mercedes", "doors" : 5 }";
3
4
ObjectMapper objectMapper = new ObjectMapper();
5
6
try {
7
8
// 转成 JsonNode, JsonNode 具有结构,可以访问字符串中对应的属性
9
JsonNode jsonNode = objectMapper.readValue(carJson, JsonNode.class);
10
11
} catch (IOException e) {
12
e.printStackTrace();
13
}
ObjectMapper
也有一个特殊的 readTree()
。它总是返回对象 JsonNode
x
1
String carJson =
2
"{ "brand" : "Mercedes", "doors" : 5 }";
3
4
ObjectMapper objectMapper = new ObjectMapper();
5
6
try {
7
8
JsonNode jsonNode = objectMapper.readTree(carJson);
9
10
} catch (IOException e) {
11
e.printStackTrace();
12
}
JsonNode
类
xxxxxxxxxx
35
1
String carJson =
2
"{ "brand" : "Mercedes", "doors" : 5," +
3
" "owners" : ["John", "Jack", "Jill"]," +
4
" "nestedObject" : { "field" : "value" } }";
5
6
ObjectMapper objectMapper = new ObjectMapper();
7
8
9
try {
10
11
// 将 String 转换为 JsonNode 对象
12
JsonNode jsonNode = objectMapper.readValue(carJson, JsonNode.class);
13
14
// JsonNode 可以通过 key 获取对应的 value
15
JsonNode brandNode = jsonNode.get("brand");
16
String brand = brandNode.asText();
17
System.out.println("brand = " + brand);
18
19
JsonNode doorsNode = jsonNode.get("doors");
20
int doors = doorsNode.asInt();
21
System.out.println("doors = " + doors);
22
23
JsonNode array = jsonNode.get("owners");
24
JsonNode jsonNode = array.get(0);
25
String john = jsonNode.asText();
26
System.out.println("john = " + john);
27
28
JsonNode child = jsonNode.get("nestedObject");
29
JsonNode childField = child.get("field");
30
String field = childField.asText();
31
System.out.println("field = " + field);
32
33
} catch (IOException e) {
34
e.printStackTrace();
35
}
14. 将 Object 转换为 JsonNode
xxxxxxxxxx
1
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
Car car = new Car();
4
car.brand = "Cadillac";
5
car.doors = 4;
6
7
// valueToTree() 区别于 readTree()
8
// readTree(String str)是将字符串转换为 JsonNode
9
JsonNode carJsonNode = objectMapper.valueToTree(car);
15. 将 JsonNode 转换为 Object
xxxxxxxxxx
1
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
String carJson = "{ "brand" : "Mercedes", "doors" : 5 }";
4
5
JsonNode carJsonNode = objectMapper.readTree(carJson);
6
7
Car car = objectMapper.treeToValue(carJsonNode);
16. 使用 ObjectMapper 读取和编写 YAML
x
1
/**
2
* 从yaml文件读取数据
3
* @throws IOException
4
*/
5
private static void reaedYamlToEmployee() throws IOException {
6
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
7
Employee employee = mapper.readValue(new File("src/test/java/com/example/jackjson/EmployeeYaml.yml"), Employee.class);
8
System.out.println(employee.getName() + "********" + employee.getEmail());
9
10
}
11
12
/**
13
* 写入yaml文件
14
* @throws IOException
15
*/
16
private static void reaedEmployeeToYaml() throws IOException {
17
//去掉三个破折号
18
ObjectMapper mapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));
19
//禁用掉把时间写为时间戳
20
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
21
22
Employee employee = new Employee("test2", "999@qq.com");
23
mapper.writeValue(new File("src/test/java/com/example/jackjson/EmployeeYamlOutput.yml"), employee);
24
}