当前位置:网站首页>Jackson parsing JSON detailed tutorial
Jackson parsing JSON detailed tutorial
2022-07-29 05:09:00 【Tonghua misses the rain】
Catalog
JSON
sketch
JSON
It's no stranger to developers , Today, WEB
service 、 Mobile application 、 Even the Internet of things is mostly based on JSON
As the format of data exchange . Study JSON
Format operation tools are essential for developers . This article will show you how to use Jackson
Open source tool library pair JSON
Perform common operations
JSON
yes JavaScript Object Notation
Abbreviation ,JSON
Is a text-based format , It can be understood as a structured data , This structured data can contain key value mappings 、 Nested objects, arrays and other information
{
"array": [
1,
2,
3
],
"boolean": true,
"color": "gold",
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d"
},
"string": "www.wdbyte.com"
}
Jackson
Introduce
Jackson
and FastJson
equally , It's a Java
language-written , Can be done JSON
Open source tool library for processing ,Jackson
It is widely used ,Spring
The frame defaults to Jackson
Conduct JSON
Handle
Jackson
There are three core packages , Namely Streaming、Databid、Annotations
, Through these bags, it is convenient to JSON
To operate
Streaming[1]
stayjackson-core
modular . Define some flow processing relatedAPI
And specificJSON
RealizationAnnotations[2]
stayjackson-annotations
modular , ContainsJackson
The annotations inDatabind[3]
stayjackson-databind
modular , stayStreaming
Package based on the implementation of data binding , Depend onStreaming
andAnnotations
package
Thanks to the Jackson
Highly scalable design , There are many common text formats and tools that are right Jackson
Corresponding adaptation of , Such as CSV、XML、YAML
etc.
Jackson
Of Maven
rely on
In the use of Jackson
when , In most cases, we only need to add jackson-databind
Dependencies , You can use Jackson
The function of , It relies on the following two packages
com.fasterxml.jackson.core:jackson-annotations
com.fasterxml.jackson.core:jackson-core
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
In order to facilitate the subsequent code demonstration of this article , We also introduce Junit
Unit testing and Lombok
In order to reduce Get/Set
Code writing
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
ObjectMapper
Object mapper
ObjectMapper
yes Jackson
The most commonly used class in the Library , It can be used for Java
Objects and JSON
Fast conversion between strings . If you used FastJson
, that Jackson
Medium ObjectMapper
Just as FastJson
Medium JSON
class
There are some common methods in this class
readValue()
Methods can be used toJSON
Deserialization of , For example, you can string 、 File stream 、 Byte stream 、 Byte arrays, etc. convert common contents intoJava
objectwriteValue()
Methods can be used toJSON
The serialization operation of , Can beJava
Object conversion toJSON
character string
Most of the time ,ObjectMapper
It works by Java Bean
Object's Get/Set
Method is mapped when converting , So write it correctly Java
Object's Get/Set
Methods are particularly important , however ObjectMapper
There are also many configurations , For example, you can configure or annotate Java
Objects and JSON
The conversion process between strings is customized . These will be introduced in the following sections
Jackson JSON
Basic operation
Jackson
As a Java
Medium JSON
Tool library , Handle JSON
String and Java
Object is its most basic and commonly used function , Here are some examples to demonstrate the usage
Jackson JSON
Serialization
Write a Person
class , Define three attributes , name 、 Age and skills
@Data
public class Person {
private String name;
private Integer age;
private List<String> skillList;
}
take Java
Object conversion to JSON
character string
public class PersonTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
void pojoToJsonString() throws JsonProcessingException {
Person person = new Person();
person.setName("aLng");
person.setAge(27);
person.setSkillList(Arrays.asList("java", "c++"));
String json = objectMapper.writeValueAsString(person);
System.out.println(json);
String expectedJson = "{\"name\":\"aLng\",\"age\":27,\"skillList\":[\"java\",\"c++\"]}";
Assertions.assertEquals(json, expectedJson);
}
}
Output JSON
character string
{
"name":"aLng","age":27,"skillList":["java","c++"]}
Jackson
You can even directly serialize JSON
String is written to file or read into byte array
mapper.writeValue(new File("result.json"), myResultObject);
// perhaps
byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
// perhaps
String jsonString = mapper.writeValueAsString(myResultObject);
Jackson JSON
Deserialization of
public class PersonTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
void jsonStringToPojo() throws JsonProcessingException {
String expectedJson = "{\"name\":\"aLang\",\"age\":27,\"skillList\":[\"java\",\"c++\"]}";
Person person = objectMapper.readValue(expectedJson, Person.class);
System.out.println(person);
Assertions.assertEquals(person.getName(), "aLang");
Assertions.assertEquals(person.getSkillList().toString(), "[java, c++]");
}
}
Output results
Person(name=aLang, age=27, skillList=[java, c++])
The above example demonstrates how to use Jackson
Put one JSON
String is anti sequenced into Java
object , Actually Jackson
For... In the file JSON
character string 、 In byte form JSON
String deserialization is also simple
For example, I prepared a JSON
Content file Person.json
{
"name": "aLang",
"age": 27,
"skillList": [
"java",
"c++"
]
}
Next, read conversion
ObjectMapper objectMapper = new ObjectMapper();
@Test
void testJsonFilePojo() throws IOException {
File file = new File("src/Person.json");
Person person = objectMapper.readValue(file, Person.class);
// perhaps
// person = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
System.out.println(person);
Assertions.assertEquals(person.getName(), "aLang");
Assertions.assertEquals(person.getSkillList().toString(), "[java, c++]");
}
Also output Person
Content
Person(name=aLang, age=27, skillList=[java, c++])
JSON
turn List
It shows JSON
Strings are single object , If JSON
It is an object list, so use Jackson
How to deal with it ?
A file already exists PersonList.json
[
{
"name": "aLang",
"age": 27,
"skillList": [
"java",
"c++"
]
},
{
"name": "darcy",
"age": 26,
"skillList": [
"go",
"rust"
]
}
]
Read it and convert it to List<Person>
ObjectMapper objectMapper = new ObjectMapper();
@Test
void fileToPojoList() throws IOException {
File file = new File("src/EmployeeList.json");
List<Person> personList = objectMapper.readValue(file, new TypeReference<List<Person>>() {
});
for (Person person : personList) {
System.out.println(person);
}
Assertions.assertEquals(personList.size(), 2);
Assertions.assertEquals(personList.get(0).getName(), "aLang");
Assertions.assertEquals(personList.get(1).getName(), "darcy");
}
You can output object content
Person(name=aLang, age=27, skillList=[java, c++])
Person(name=darcy, age=26, skillList=[go, rust])
JSON
turn Map
JSON
turn Map
We don't have an object Java
Object is very useful , How to use it Jackson
hold JSON
Turn the text into Map
object
ObjectMapper objectMapper = new ObjectMapper();
@Test
void jsonStringToMap() throws IOException {
String expectedJson = "{\"name\":\"aLang\",\"age\":27,\"skillList\":[\"java\",\"c++\"]}";
Map<String, Object> employeeMap = objectMapper.readValue(expectedJson, new TypeReference<Map>() {
});
System.out.println(employeeMap.getClass());
for (Entry<String, Object> entry : employeeMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
Assertions.assertEquals(employeeMap.get("name"), "aLang");
}
You can see Map
Output result of
class java.util.LinkedHashMap
name:aLang
age:27
skillList:[java, c++]
Jackson
Ignored fields for
If it's going on JSON
turn Java
Object time ,JSON
In the Java
Properties that do not exist in the class , Then you will encounter com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
abnormal
Use objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
You can ignore non-existent attributes
ObjectMapper objectMapper = new ObjectMapper();
@Test
void jsonStringToPojoIgnoreProperties() throws IOException {
// UnrecognizedPropertyException
String json = "{\"yyy\":\"xxx\",\"name\":\"aLang\",\"age\":27,\"skillList\":[\"java\",\"c++\"]}";
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Person person = objectMapper.readValue(json, Person.class);
System.out.printf(person.toString());
Assertions.assertEquals(person.getName(), "aLang");
Assertions.assertEquals(person.getSkillList().toString(), "[java, c++]");
}
Normal output
Person(name=aLang, age=27, skillList=[java, c++])
Jackson
Date format for
stay Java 8
Before, we usually used java.util.Date
Class to handle time , But in Java 8
A new time class was introduced during release java.time.LocalDateTime
. The two are Jackson
The treatment in is slightly different
First create a with two time type attributes Order
class
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
private Integer id;
private Date createTime;
private LocalDateTime updateTime;
}
Date
type
Now let's create a new test case to test two types of time JSON
transformation
class OrderTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
void testPojoToJson0() throws JsonProcessingException {
Order order = new Order(1, new Date(), null);
String json = objectMapper.writeValueAsString(order);
System.out.println(json);
order = objectMapper.readValue(json, Order.class);
System.out.println(order.toString());
Assertions.assertEquals(order.getId(), 1);
}
}
In this test code , We only initialized Date
Type of time , Here's the output
{
"id":1,"createTime":1658320852395,"updateTime":null}
Order(id=1, createTime=Wed Jul 20 20:40:52 CST 2022, updateTime=null)
You can see that it is normal JSON
Serialization and deserialization , however JSON
The time in is a timestamp format , Maybe not what we want
LocalDateTime
type
Why not set LocalDateTime
What about the type of time ? Because by default LocalDateTime
Class JSON
The conversion will encounter an error
class OrderTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
void testPojoToJson() throws JsonProcessingException {
Order order = new Order(1, new Date(), LocalDateTime.now());
String json = objectMapper.writeValueAsString(order);
System.out.println(json);
order = objectMapper.readValue(json, Order.class);
System.out.println(order.toString());
Assertions.assertEquals(order.getId(), 1);
}
}
After running, you will encounter an error
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Java 8 date/time type `java.time.LocalDateTime` not supported by default:
add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
to enable handling (through reference chain: com.wdbyte.jackson.Order["updateTime"])
Here we need to add the corresponding data binding support package
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.3</version>
</dependency>
And then in defining ObjectMapper
Through findAndRegisterModules()
Method to register dependencies
class OrderTest {
ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules();
@Test
void testPojoToJson() throws JsonProcessingException {
Order order = new Order(1, new Date(), LocalDateTime.now());
String json = objectMapper.writeValueAsString(order);
System.out.println(json);
order = objectMapper.readValue(json, Order.class);
System.out.println(order.toString());
Assertions.assertEquals(order.getId(), 1);
}
}
Normal serialization and deserialization logs can be obtained by running , However, the time format after serialization is still strange
{
"id":1,"createTime":1658321191562,"updateTime":[2022,7,20,20,46,31,567000000]}
Order(id=1, createTime=Wed Jul 20 20:46:31 CST 2022, updateTime=2022-07-20T20:46:31.567)
Time format
By using annotations on fields @JsonFormat
Customize the time format
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
private Integer id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
private LocalDateTime updateTime;
}
Run the above column again to get the time formatted JSON
character string
{
"id":1,"createTime":"2022-07-20 20:49:46","updateTime":"2022-07-20 20:49:46"}
Order(id=1, createTime=Wed Jul 20 20:49:46 CST 2022, updateTime=2022-07-20T20:49:46)
Jackson
Common comments
@JsonIgnore
Use @JsonIgnore
One can be ignored Java
Properties in objects , It will not participate in JSON
Serialization and deserialization
@Data
public class Cat {
private String name;
@JsonIgnore
private Integer age;
}
Write unit test classes
class CatTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
void testPojoToJson() throws JsonProcessingException {
Cat cat = new Cat();
cat.setName("Tom");
cat.setAge(2);
String json = objectMapper.writeValueAsString(cat);
System.out.println(json);
Assertions.assertEquals(json, "{\"name\":\"Tom\"}");
cat = objectMapper.readValue(json, Cat.class);
Assertions.assertEquals(cat.getName(), "Tom");
Assertions.assertEquals(cat.getAge(), null);
}
}
Output results age
The attribute is null
{
"name":"Tom"}
@JsonGetter
Use @JsonGetter
It can be in the right place Java
Object to carry out JSON
Custom attribute name when serializing
@Data
public class Cat {
private String name;
private Integer age;
@JsonGetter(value = "catName")
public String getName() {
return name;
}
}
Write unit test classes to test
class CatTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
void testPojoToJson2() throws JsonProcessingException {
Cat cat = new Cat();
cat.setName("Tom");
cat.setAge(2);
String json = objectMapper.writeValueAsString(cat);
System.out.println(json);
Assertions.assertEquals(json, "{\"age\":2,\"catName\":\"Tom\"}");
}
}
Output results ,name
It's set to catName
{
"age":2,"catName":"Tom"}
@JsonSetter
Use @JsonSetter
It can be in the right place JSON
Set when deserializing JSON
Medium key
And Java
Attribute mapping
@Data
public class Cat {
@JsonSetter(value = "catName")
private String name;
private Integer age;
@JsonGetter(value = "catName")
public String getName() {
return name;
}
}
Write unit test classes to test
class CatTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
void testPojoToJson2() throws JsonProcessingException {
String json = "{\"age\":2,\"catName\":\"Tom\"}";
Cat cat = objectMapper.readValue(json, Cat.class);
System.out.println(cat.toString());
Assertions.assertEquals(cat.getName(), "Tom");
}
}
Output results
Cat(name=Tom, age=2)
@JsonAnySetter
Use @JsonAnySetter
It can be in the right place JSON
When deserializing , For all of you in Java
The properties that do not exist in the object are processed logically , The following code demonstrates storing non-existent attributes in a Map
Collection
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String name;
private Integer age;
private Map<String, Object> diyMap = new HashMap<>();
@JsonAnySetter
public void otherField(String key, String value) {
this.diyMap.put(key, value);
}
}
Write unit test cases
class StudentTest {
private ObjectMapper objectMapper = new ObjectMapper();
@Test
void testJsonToPojo() throws JsonProcessingException {
Map<String, Object> map = new HashMap<>();
map.put("name", "aLang");
map.put("age", 18);
map.put("skill", "java");
String json = objectMapper.writeValueAsString(map);
System.out.println(json);
Student student = objectMapper.readValue(json, Student.class);
System.out.println(student);
Assertions.assertEquals(student.getDiyMap().get("skill"), "java");
}
}
You can see in the output JSON
Medium skill
Because the attribute is not Java
class Student
in , So it was put diyMap
aggregate
{
"skill":"java","name":"aLang","age":18}
Student(name=aLang, age=18, diyMap={
skill=java})
@JsonAnyGetter
Use @JsonAnyGetter
It can be in the right place Java
When the object is serialized , Make one of them Map
Assemble as JSON
Source of attributes in
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student {
@Getter
@Setter
private String name;
@Getter
@Setter
private Integer age;
@JsonAnyGetter
private Map<String, Object> initMap = new HashMap() {
{
put("a", 111);
put("b", 222);
put("c", 333);
}};
}
Write unit test cases
class StudentTest {
private ObjectMapper objectMapper = new ObjectMapper();
@Test
void testPojoToJsonTest() throws JsonProcessingException {
Student student = new Student();
student.setName("aLang");
student.setAge(20);
String json = objectMapper.writeValueAsString(student);
System.out.println(json);
Assertions.assertEquals(json,"{\"name\":\"aLang\",\"age\":20,\"a\":111,\"b\":222,\"c\":333}");
}
}
Output results
{
"name":"aLang","age":20,"a":111,"b":222,"c":333}
Jackson
summary
Jackson
yesJava
Compare trafficJSON
One of the processing libraries , It isSpring
DefaultJSON
ToolsJackson
It is mainly composed of three modules ,Streaming API 、Annotations
andData Binding
Jackson
MediumObjectMapper
Class is very powerful , Can be doneJSON
Related treatment , At the same time, you can customize the conversion logic in combination with comments and configuration .Jackson
Good scalability , Such asCSV、XML、YAML
Format processing is all rightJackson
There are corresponding adaptations, etc
边栏推荐
- Use jupyter (2) to establish shortcuts to open jupyter and common shortcut keys of jupyter
- Open the tutorial of adding and modifying automatically playing music on the open zone website
- 缓存穿透、缓存击穿、缓存雪崩以及解决方法
- AttributeError: ‘module‘ object has no attribute ‘create_connection‘
- 自贸经济中架起的“隐形桥梁”:国货精品与中国AI力量
- P5714 [deep foundation 3. Case 7] obesity
- 2021-10-11
- Create a mindscore environment in modelars, install mindvision, and conduct in-depth learning and training (Huawei)
- Mapper agent development
- What are the core features of the digital transformation of state-owned construction enterprises?
猜你喜欢
Let you understand several common traffic exposure schemes in kubernetes cluster
Huawei ilearning AI mathematics foundation course notes
Mapper agent development
Solution | get the relevant information about the current employees' highest salary in each department |
如何安装office2010安装包?office2010安装包安装到电脑上的方法
那个准时上下班,从不愿意加班加点的人,在我前面升职了...
WPS插入超链接无法打开,提示“无法打开指定文件”怎么办!
How to add a map to the legendary server
stack和queue和优先级队列(大堆和小堆)模拟实现和仿函数讲解
ODOO开发教程之透视表
随机推荐
IDEA中使用注解Test
WPS insert hyperlink cannot be opened. What should I do if I prompt "unable to open the specified file"!
Unity Metaverse(三)、Protobuf & Socket 实现多人在线
缓存穿透、缓存击穿、缓存雪崩以及解决方法
MySQL time calculation function
Simple user-defined authentication interface rules
荣耀2023内推,内推码ambubk
pytorch学习笔记
Deadlock to be resolved
ODOO开发教程之图表
Use annotation test in idea
How to debug UDP port
The representation of time series analysis: is the era of learning coming?
Wechat picture identification
关于thymeleaf的配置与使用
JS daily question (11)
Diagram of odoo development tutorial
office2010每次打开都要配置进度怎么解决?
SparkSql批量插入或更新,保存数据到Mysql中
五个关联分析,领略数据分析师一大重要必会处理技能