“This is the 12th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

Author: Tangyuan

Personal blog: Javalover.cc

preface

Jackson is a json library that comes with SpringBootStarter, so it’s necessary to learn Jackson.

In Jackson, the core is ObjectMapper, which is responsible for serializing and deserializing Java objects;

directory

  1. Add the dependent
  2. Using ObjectMapper
  3. Exception handling

The body of the

1. Add dependencies

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.1</version>
</dependency>
Copy the code

If not, the latest version is usually used, in this case 2.13.1;

Annotations the databind dependency contains the jackson-core and Jackson-Annotations libraries, as shown below:

<dependencies>
    <! -- Builds on core streaming API; also needs core annotations -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <! -- 06-Mar-2017, tatu: Although bom provides for dependencies, some legacy usage seems to benefit from actually specifying version here in case it is dependent on transitively -->
        <version>${jackson.version.annotations}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version.core}</version>
    </dependency>
Copy the code

2. Using ObjectMapper

ObjectMapper is responsible for serializing and deserializing objects;

Serialize Java objects into JSON strings, and parse JSON strings into Java objects

2.1 Serialization:

Here we define a Java object, User, as follows:

@Data
public class User {

    private String username;

    private String password;

}
Copy the code

We then create a User object and serialize it as a Json string:

User user = new User("admin"."123");
ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(user);
System.out.println(str);
Copy the code

The output is as follows:

{"username":"admin"."password":"123"}
Copy the code

2.2 Deserialization

That is, converting a Json string into a Java object;

If we know the object type at serialization, we can parse it directly to the original type;

If you do not know, there are other ways to parse, such as Map or JsonNode;

Parse to the original Java type:

Here we use the json string printed above directly:

User readValue = objectMapper.readValue(str, User.class);
System.out.println(readValue);
Copy the code

The output is as follows:

User(username=admin, password=123)	
Copy the code

Parse to a JsonNode object:

If we don’t know the type of the Java object, we can use Jackson’s built-in JsonNode object, similar to map:

JsonNode jsonNode = objectMapper.readTree(str);
String username = jsonNode.get("username").asText();
String password = jsonNode.get("password").asText();
System.out.println("username:"+username+", password:"+password);
Copy the code

As you can see, this JsonNode operates much like Map, but more flexibly than Map. This includes retrieving values (which can be obtained through indexes), transforming values, etc., which are encapsulated here for you;

Parsed as a List:

If you want to parse a JSON array string, use the TypeReference class.

Here we create a JSON array and serialize it;

ArrayList<User> users = new ArrayList<>();
users.add(user);
users.add(user);
String jsonArrStr = objectMapper.writeValueAsString(users);
System.out.println(jsonArrStr);

List<User> userList = objectMapper.readValue(jsonArrStr, new TypeReference<List<User>>(){});
System.out.println(userList);
Copy the code

Here we use the knowledge of generics, please refer to generics – Details – Nuggets in Java (juejin. Cn)

3. Exception handling

Sometimes when parsing a Json string, ObjectMapper will give an error if it has extra attributes attached;

Let’s add a property email to the Json string above and parse it as a User object:

String strNew = "{\"username\":\"admin\",\"password\":\"123\", \"email\": \"xxx.mail\"}";
User user1 = objectMapper.readValue(strNew, User.class);
System.out.println(user1);
Copy the code

In this case, an error message is displayed:

This means that the email attribute cannot be resolved, and it suggests a solution by marking it as an ignored attribute.

If an error is reported when parsing an unknown attribute, we set it to no (default true).

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
User user2 = objectMapper.readValue(strNew, User.class);
System.out.println(user2);
Copy the code

Now it’s fine to run;

Of course, there are many other configurations, as follows:

conclusion

This article covers the basics of Jackson, including serialization and deserialization;

Examples of exception handling, such as resolving unknown attributes without reporting an error, are also introduced.