Jackson - Convert Java Object to/from JSON Example

In this article, I show you how to how to use Jackson-databind API for binding Java Object to JSON and JSON data to Java Object. This is a common task for Java developers to convert JSON to Java objects and vice-versa so I show you how to do that with examples.
The ObjectMapper class provides the functionality for reading and writing JSON, either to or from basic  POJOs.
Before getting started, let's define the required Jackson API dependencies.

Dependencies

Let’s first add the following dependencies to the pom.xml:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
This dependency will also transitively add the following libraries to the classpath:
  • jackson-annotations-2.9.8.jar
  • jackson-core-2.9.8.jar
  • jackson-databind-2.9.8.jar
Always use the latest versions on the Maven central repository for Jackson databind.

Converting Java Object to JSON Example

Here is an example of creating JSON from Java object using the ObjectMapper.writeValueXXX() methods.

Post.java

package net.javaguides.jackson.pojotojson;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class Post {
    private Long id;
    private String title;
    private String description;
    private String content;
    private Date postedAt = new Date();
    private Date lastUpdatedAt = new Date();
    private Set < Tag > tags = new HashSet < > ();

    public Post() {

    }

    public Post(String title, String description, String content) {
        this.title = title;
        this.description = description;
        this.content = content;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getPostedAt() {
        return postedAt;
    }

    public void setPostedAt(Date postedAt) {
        this.postedAt = postedAt;
    }

    public Date getLastUpdatedAt() {
        return lastUpdatedAt;
    }

    public void setLastUpdatedAt(Date lastUpdatedAt) {
        this.lastUpdatedAt = lastUpdatedAt;
    }

    public Set < Tag > getTags() {
        return tags;
    }

    public void setTags(Set < Tag > tags) {
        this.tags = tags;
    }
}

Tag.java

package net.javaguides.jackson.pojotojson;

public class Tag {
    private Long id;
    private String name;

    public Tag() {

    }

    public Tag(Long id, String name) {
        super();
        this.id = id;
        this.name = name;
    }


    public Tag(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

JacksonPojoToJson.java

package net.javaguides.jackson.pojotojson;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * Convert Java to Json using Jackson API
 * @author Ramesh Fadatare
 *
 */
public class JacksonPojoToJson {
    public static void main(String[] args) throws IOException {
        // Create ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // create a post
        Post post = new Post();
        post.setTitle("Jackson JSON API Guide");
        post.setId(100 L);
        post.setDescription("Post about Jackson JSON API");
        post.setContent("HTML content here");
        post.setLastUpdatedAt(new Date());
        post.setPostedAt(new Date());

        // create some predefined tags
        Set < Tag > tags = new HashSet < > ();
        Tag java = new Tag(1 L, "Java");
        Tag jackson = new Tag(2 L, "Jackson");
        Tag json = new Tag(3 L, "JSON");
        tags.add(java);
        tags.add(jackson);
        tags.add(json);

        // set tags to post
        post.setTags(tags);

        // Convert object to JSON string
        String postJson = mapper.writeValueAsString(post);
        System.out.println(postJson);

        // Save JSON string to file
        FileOutputStream fileOutputStream = new FileOutputStream("post.json");
        mapper.writeValue(fileOutputStream, post);
        fileOutputStream.close();
    }
}
Output:
{
  "id" : 100,
  "title" : "Jackson JSON API Guide",
  "description" : "Post about Jackson JSON API",
  "content" : "HTML content here",
  "postedAt" : 1556025668077,
  "lastUpdatedAt" : 1556025668077,
  "tags" : [ {
    "id" : 3,
    "name" : "JSON"
  }, {
    "id" : 1,
    "name" : "Java"
  }, {
    "id" : 2,
    "name" : "Jackson"
  } ]
}
Note that we can also write JSON to external file. In this example, we are writing JSON to "post.json" file.

Converting JSON to Java Object

Here is an example of converting JSON to Java object using the ObjectMapper.readValue() methods. In this example, we are reading JSON from external "post.json" file and converting it into Java Object:
package net.javaguides.jackson.jsontopojo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.javaguides.jackson.pojotojson.Post;
import net.javaguides.jackson.pojotojson.Tag;

/**
 * Convert JSON to Java object using Jackson
 * @author Ramesh Fadatare
 *
 */
public class JacksonJsonToPojo {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();

        // Read JSON file and convert to java object
        InputStream fileInputStream = new FileInputStream("post.json");
        Post post = mapper.readValue(fileInputStream, Post.class);
        fileInputStream.close();

        // print post object
        System.out.println("Printing post details");
        System.out.println(post.getId());
        System.out.println(post.getTitle());
        System.out.println(post.getDescription());
        System.out.println(post.getContent());
        System.out.println(post.getLastUpdatedAt());
        System.out.println(post.getPostedAt());

        // print tags of this post
        System.out.println("Printing tag details of post :: " + post.getTitle());
        for (Iterator < Tag > iterator = post.getTags().iterator(); iterator.hasNext();) {
            Tag tag = (Tag) iterator.next();

            System.out.println(tag.getId());
            System.out.println(tag.getName());

        }
    }
}
Output:
Printing post details
100
Jackson JSON API Guide
Post about Jackson JSON API
HTML content here
Tue Apr 23 18:51:08 IST 2019
Tue Apr 23 18:51:08 IST 2019
Printing tag details of post :: Jackson JSON API Guide
2
Jackson
1
Java
3
JSON

Comments