How to convert object to / from JSON using Jackson

  • 17 July 2017
  • ADM

 

How to convert object to / from JSON using Jackson - images/logos/java.jpg

 

Here is a simple example of converting objects into JSON strings and back using Jackson.

Dependencies

Download and add the jar file as dependency for your project.

For Maven users add the Jackson dependency in your pom.xml file

<!-- http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.4</version>
</dependency>

Example

For this tutorials, I will use 2 POJO classes: User and Permission and one class as the test. Both POJO classes are copied from How to convert object to / from JSON using Gson tutorial.

Permission.java
package com.admfactory.jackson;

public class Permission {
    private String name;

    /**
     * 
     * Constructs a new <code>Permission</code> instance. Needed for Jackson to
     * create the instance from String.
     */
    public Permission() {

    }

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

    public String getName() {
	return name;
    }

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

User.java will use Permission.java as embedded object.

package com.admfactory.jackson;

import java.util.ArrayList;
import java.util.List;

public class User {
    private String username;
    private String email;
    private String password;
    private List<Permission> permissions;

    /**
     * 
     * Constructs a new <code>User</code> instance. Needed for Jackson to create
     * the instance from String.
     */
    public User() {

    }

    public String getUsername() {
	return username;
    }

    public void setUsername(String username) {
	this.username = username;
    }

    public String getEmail() {
	return email;
    }

    public void setEmail(String email) {
	this.email = email;
    }

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public List<Permission> getPermissions() {
	return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
	this.permissions = permissions;
    }

    /**
     * Method used to add a permission to the array.
     *
     * @param p
     *            {@link Permission} object
     */
    public void addPermission(Permission p) {
	/** Check if the array is null, if yes create a new array */
	if (this.permissions == null)
	    this.permissions = new ArrayList<Permission>();
	this.permissions.add(p);
    }
}

Note: in order to create the object from JSON string, Jackson library required that each model class to have the default constructor.

JacksonTest.java used as test class.

package com.admfactory.jackson;

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

public class JacksonTest {

    public static void main(String[] args) throws Exception {
	/** Create the mapper object */
	ObjectMapper mapper = new ObjectMapper();
	//mapper.enable(SerializationFeature.INDENT_OUTPUT);
	
	System.out.println("Object to JSON String Test using Jackson");

	/** Create a user object */
	User user = new User();
	user.setUsername("johndoe");
	user.setEmail("john.doe@admfactory.com");
	user.setPassword("a1234");

	/** Add some permission objects as embedded objects */
	Permission p1 = new Permission("add.user");
	Permission p2 = new Permission("delete.user");
	Permission p3 = new Permission("modify.user");

	user.addPermission(p1);
	user.addPermission(p2);
	user.addPermission(p3);

	/** Get the string from the object and print it on the console */
	String string = mapper.writeValueAsString(user);
	System.out.println("JSON String: " + string);

	System.out.println();
	System.out.println("JSON String to Object Test");

	/** Use the string printed to create a new object */
	User u = mapper.readValue(string, User.class);

	/** Print one variable to the console */
	System.out.println("Username : " + u.getUsername());

	/** Print one embedded variable to the console */
	System.out.println("First permission: " + u.getPermissions().get(0).getName());
    }
}

For more details please follow the comments from the source code.

Output

Object to JSON String Test using Jackson
JSON String: {"username":"johndoe","email":"john.doe@admfactory.com","password":"a1234","permissions":[{"name":"add.user"},{"name":"delete.user"},{"name":"modify.user"}]}

JSON String to Object Test
Username : johndoe
First permission: add.user

Conclusions

As you can see the string output is on a single line. If you need to have a pretty print for your JSON string replace the ObjectMapper object creating line from

/** Create the mapper object */
ObjectMapper mapper = new ObjectMapper();

to

/** Create the mapper object */
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

And now the output will be in a human readable format.

JSON String: {
  "username" : "johndoe",
  "email" : "john.doe@admfactory.com",
  "password" : "a1234",
  "permissions" : [ {
    "name" : "add.user"
  }, {
    "name" : "delete.user"
  }, {
    "name" : "modify.user"
  } ]
}

 

References