In an earlier article, I wrote about reading and writing JSON in Java by using multiple JSON processing libraries like JSON.simple, Jackson, Moshi, and Gson.

In this article, you'll learn how to read and write JSON using Jackson. Jackson is a popular open-source library for processing JSON in Java. It provides different APIs like ObjectMapper, ObjectParser, and JsonGenerator.

We can read JSON from multiple resources like a file, a string variable, or a network. The ObjectMapper class can be used to convert a Java Object to its JSON representation.

Dependencies

To add Jackson to your Gradle project, add the following dependency to the build.gradle file:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.0'

For Maven, include the below dependency to your pom.xml file:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</version>
</dependency>

Create Java Class

Let us create a simple Java class named Book that we will use to convert Java Objects to JSON and back:

Book.java

public class Book {

    private String title;
    private String isbn;
    private long year;
    private String[] authors;

    public Book() {
    }

    public Book(String title, String isbn, long year, String[] authors) {
        this.title = title;
        this.isbn = isbn;
        this.year = year;
        this.authors = authors;
    }

    // getters and setters, equals(), toString() .... (omitted for brevity)
}

Convert Java Object to JSON String

To convert a Java Object to a JSON string, you can use the writeValueAsString() method of ObjectMapper:

try {
    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[]{"Bruce Eckel"});

    // convert book object to JSON
    String json = new ObjectMapper().writeValueAsString(book);

    // print JSON string
    System.out.println(json);

} catch (Exception ex) {
    ex.printStackTrace();
}

You should see the following output printed on the console:

{"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]}

Convert Java Object to JSON File

The ObjectMapper class provides the writeValue() method for converting a Java Object to a JSON file:

try {
    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[]{"Bruce Eckel"});

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert book object to JSON file
    mapper.writeValue(Paths.get("book.json").toFile(), book);

} catch (Exception ex) {
    ex.printStackTrace();
}

Convert List of Java Objects to JSON Array

Just like a single Java Object conversion to JSON, you can also convert a list of Java Objects to their JSON representation using the same writeValue() method:

try {
    // create books list
    List<Book> books = Arrays.asList(
            new Book("Thinking in Java", "978-0131872486", 1998,
                    new String[]{"Bruce Eckel"}),
            new Book("Head First Java", "0596009208", 2003,
                    new String[]{"Kathy Sierra", "Bert Bates"})
    );

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert books object to JSON file
    mapper.writeValue(Paths.get("books.json").toFile(), books);

} catch (Exception ex) {
    ex.printStackTrace();
}

Java Object to Pretty Print JSON File

Jackson API can also write pretty print JSON by using the DefaultPrettyPrinter class:

try {
    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[]{"Bruce Eckel"});

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // create an instance of DefaultPrettyPrinter
    ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());

    // convert book object to JSON file
    writer.writeValue(Paths.get("book.json").toFile(), book);

} catch (Exception ex) {
    ex.printStackTrace();
}

The above code should write the following pretty print JSON to book.json:

{
  "title" : "Thinking in Java",
  "isbn" : "978-0131872486",
  "year" : 1998,
  "authors" : [ "Bruce Eckel" ]
}

Convert Java Map to JSON File

Jackson is not just limited to Java Objects. You can even convert a Java Map into a JSON file using ObjectMapper:

try {
    // create a book map
    Map<String, Object> map = new HashMap<>();
    map.put("title", "Thinking in Java");
    map.put("isbn", "978-0131872486");
    map.put("year", 1998);
    map.put("authors", new String[]{"Bruce Eckel"});

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert book map to JSON file
    mapper.writeValue(Paths.get("book.json").toFile(), map);

} catch (Exception ex) {
    ex.printStackTrace();
}

Convert JSON String to Java Object

To convert a JSON string into a Java Object, you can use the readValue() method from ObjectMapper:

try {
    // JSON string
    String json = "{\"title\":\"Thinking in Java\",\"isbn\":\"978-0131872486\"" +
            ",\"year\":1998,\"authors\":[\"Bruce Eckel\"]}";

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert a JSON string to a Book object
    Book book = mapper.readValue(json, Book.class);

    // print book
    System.out.println(book);

} catch (Exception ex) {
    ex.printStackTrace();
}

Convert JSON File to Java Object

To read a JSON file into a Java Object, you can use the same readValue() method:

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert a JSON string to a Book object
    Book book = mapper.readValue(Paths.get("book.json").toFile(), Book.class);

    // print book
    System.out.println(book);

} catch (Exception ex) {
    ex.printStackTrace();
}

Convert JSON Array to List of Java Objects

The following example demonstrates how to convert a JSON array to a list of Java Objects:

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON array to list of books
    List<Book> books = Arrays.asList(mapper.readValue(Paths.get("books.json").toFile(), Book[].class));

    // print books
    books.forEach(System.out::println);

} catch (Exception ex) {
    ex.printStackTrace();
}

Convert JSON File to Java Map

Just like a JSON file to Java Object conversion, you can also convert a JSON file to a Java Map with the same properties and keys, as follows:

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON file to map
    Map<?, ?> map = mapper.readValue(Paths.get("book.json").toFile(), Map.class);

    // print map entries
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }

} catch (Exception ex) {
    ex.printStackTrace();
}

@JsonProperty Annotation

By default, Jackson uses the class field names as JSON property names. With the @JsonProperty annotation, you can specify a custom JSON property name:

public class Book {

    private String title;
    @JsonProperty("BookISBN")
    private String isbn;
    private long year;
    private String[] authors;
		
    // ...
}

Now, if you convert a Book object to JSON, the output should look like the below:

{"title":"Thinking in Java","BookISBN":"978-0131872486","year":1998,"authors":["Bruce Eckel"]}

@JsonIgnore and @JsonIgnoreProperties Annotations

By default, Jackson attempts to parse all fields, even static or transient fields. By using the @JsonIgnore annotation, you can specify fields that should be ignored while serializing and deserializing JSON:

public class Book {

    private String title;
    private String isbn;
    @JsonIgnore
    private long year;
    private String[] authors;
		
    // ...
}

Similarly, the @JsonIgnoreProperties annotation is used to specify a list of ignored properties on the class level:

@JsonIgnoreProperties({"year", "authors"})
public class Book {

    private String title;
    private String isbn;
    private long year;
    private String[] authors;
		
    // ...
}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.