Self-built blog address: bytelife.net, welcome visit! This article is a blog automatically synchronized articles, for a better reading experience, you are advised to go to my blog 👇

Link to this article: bytelife.net/articles/47… Copyright Notice: All articles on this blog are licensed BY-NC-SA unless otherwise stated. Reprint please indicate the source!


In the process of Web development, using JSON can help us develop our applications more easily. So how do you convert Java instances to JSON (serialization and deserialization) in the Java language? The popular JSON third-party libraries include Jackson, Gson, Fastjson, etc. This article will briefly introduce how to use Jackson to parse and serialize JSON.

1. Get Jackson

Jackson can be obtained either through Maven or directly by downloading the JAR package. Usually, you only need to download the Jackson-core package for Jackson. If you want to use more features (such as annotations), you need to download another JAR package. Jackson provides us with the following JAR packages:

  1. Jackson-core.jar — Core package (required), provides API based on “stream pattern” parsing.
  2. Jackson-databind — Data binding package (optional), providing apis based on object binding and tree model.
  3. Annotations — Optional package, which provides annotations.

The latest version of Jackson is 2.8.2.

1. Obtain it from Maven

Using Maven to get Jackson is very easy. Simply add the following dependencies to pom.xml:

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

2. Directly download the JAR package

There are two ways to download jar packages directly:

  1. Central Maven repository:repo1.maven.org/maven2/com/…
  2. Wiki:github.com/FasterXML/j…

Java classes for testing

To help us learn and test Jackson, we will first prepare a Java class User with the following code:

// The User class for JSON serialization and deserialization
import java.util.Date;

public class User {
	private String name;
	private Integer age;
	private Date birthday;
	private String email;
	
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public Integer getAge(a) {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	public Date getBirthday(a) {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public String getEmail(a) {
		return email;
	}
	public void setEmail(String email) {
		this.email = email; }}Copy the code

JSON serialization (Java object to JSON)

Before using Jackson, let’s take a look at one of Jackson’s core classes, ObjectMapper, whose API is used for almost all of our operations. ObjectMapper has several JSON serialization methods, which can save JSON strings to different media such as File, OutputStream, etc.

  • WriteValue (File arg0, Object arg1) converts arg1 into a JSON sequence and stores it in the arg0 File.
  • WriteValue (OutputStream arg0, Object arg1) converts arg1 into a json sequence and stores it in the arg0 OutputStream.
  • WriteValueAsBytes (Object arg0) converts arg0 into a JSON sequence and outputs the result as a byte array.
  • WriteValueAsString (Object arg0) converts arg0 into a JSON sequence and outputs the result as a string.

WriteValueAsString (Object obj) converts a Java Object to a JSON string, using the following code:

package cn.javacodes.jackson.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/** * Created by huzha on 2016-09-07. */
public class JacksonTest {
    public static void main(String[] args) throws JsonProcessingException, ParseException {
        User user = new User();
        user.setName("Jeffrey");
        user.setEmail("[email protected]");
        user.setAge(20);
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1995-08-23"));

        
        ObjectMapper mapper = new ObjectMapper();
        / / the User class JSON
        / / output results: {" name ":" Jeffrey ", "age" : 20, "birthday" : 809107200000, "email" : "[email protected]"}
        String json = mapper.writeValueAsString(user);
        System.out.println(json);

        //Java collection to JSON
        / / output: [{" name ":" Jeffrey ", "age" : 20, "birthday" : 809107200000, "email" : "[email protected]"}]
        List<User> users = newArrayList<User>(); users.add(user); String jsonlist = mapper.writeValueAsString(users); System.out.println(jsonlist); }}Copy the code

JSON deserialization (JSON to Java object)

Jackson provides us with a number of methods for JSON deserialization, among which the most common ones are as follows:

We can parse files, urls, strings, streams, byte arrays, etc., as data sources.

package cn.javacodes.jackson.test;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.ParseException;

/** * Created by huzha on 2016-09-07. */
public class JacksonTest {
    public static void main(String[] args) throws IOException, ParseException {
        String json = "{"name":"Jeffrey","age": 20."birthday": 809107200000,"email":"xxx@xxx.com"}";
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json,User.class);
        User{name='Jeffrey', age=20, birthday=Wed Aug 23 00:00:00 CST 1995, email='[email protected]'}System.out.println(user.toString()); }}Copy the code

5. JSON annotations

Jackson provides a series of annotations to help you control JSON serialization and deserialization. Here are some common annotations. @jsonignore This annotation is used on a property to ignore it during JSON operations. @jsonFormat This annotation is used on attributes to convert the Date type directly to the desired format, such as @jsonFormat (pattern = “YYYY-MM-DD HH-MM-SS “). @jsonProperty This annotation is used on a property to serialize the name of the property to another name, such as the trueName property to name, @jsonProperty (“name”). For example, we made some changes to the User class, and modified part of the code as follows:

    // Ignore this property when serializing
    @JsonIgnore
    private Integer age;

    // Format the date
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    // Serialize email to E-mail
    @JsonProperty("e-mail")
    private String email;
Copy the code

The above serialization method is converted again, and the output result is as follows:

{"name":"Jeffrey"."birthday":"1995-08-22"."e-mail":"[email protected]"}
Copy the code

You can see that the annotations are working.

conclusion

Using Jackson to parse and serialize JSON in Java is very convenient, and Jackson is very good in terms of performance. At the heart of manipulating JSON with Jackson is the ObjectMapper class, an instance of which almost all of our operations are performed. Of course, if you’re interested, you can also try using Gson or FastJson to manipulate JSON, which is pretty much the same.