Java JSON Serialization and Deserialization

In modern software development, the conversion of Java objects to JSON and JSON String to Java Objects is essential for seamless data interchange. In this post we will learn to implement Java JSON serialization and deserialization, using popular libraries such as Jackson.

Dependency

First, add Jackson as a dependency to our project:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>{latest_version}</version>
</dependency>

Alternatively, you can copy Jakson Databind dependency from maven repository.

Convert Java Object to JSON String

To start, let’s explore how to convert Java objects to JSON strings using Jackson library. In this example, we will convert Java object to JSON using ObjectMapper.

Now, let’s consider an example where we have a Person class:

package com.codersathi;

public class Person {

	private String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}
package com.codersathi;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
	public static void main(String[] args) throws Exception {
		convertJavaObjectToJSONString();
	}

	private static void convertJavaObjectToJSONString() throws JsonProcessingException {
		Person person = new Person("Coder Sathi", 30);
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonString = objectMapper.writeValueAsString(person);
		System.out.println(jsonString);
	}
}

Output

{"name":"Coder Sathi","age":30}

Convert JSON String to Java Object

Next, let’s discuss deserializing JSON strings into Java objects using Jackson. Similarly, we will convert JSON String to Java object using ObjectMapper.

Following is an example of how we can achieve this:

package com.codersathi;

public class Main {
	public static void main(String[] args) throws Exception {
		convertJavaObjectToJSONString();
		convertJSONStringToJavaObject();
	}

	private static void convertJSONStringToJavaObject()
			throws JsonMappingException, JsonProcessingException {
		String json = "{\"name\":\"Coder Sathi\",\"age\":30}";
		ObjectMapper objectMapper = new ObjectMapper();
		Person person = objectMapper.readValue(json, Person.class);
		System.out.println(person.getName()); // Output: Coder Sathi
		System.out.println(person.getAge()); // Output: 30
	}


}

Error Cannot construct instance of

When we run the code above it will throw an exception Cannot construct instance of.

The complete error looks like below:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.codersathi.Person` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"name":"Coder Sathi","age":30}"; line: 1, column: 2]

This is because, while converting JSON String to Java Object Jackson expects default constructor for Java Class. In our case Person class.

Now, if we add default constructor in Person class then we see the expected output.

Java JSON Serialization and Deserialization example

See the complete example of Converting Java Object to JSON and vice versa below:

package com.codersathi;

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

class Person {

	private String name;
	private int age;

	public Person() {
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

public class Main {
	public static void main(String[] args) throws Exception {
		convertJavaObjectToJSONString();
		convertJSONStringToJavaObject();
	}

	private static void convertJSONStringToJavaObject()
			throws JsonMappingException, JsonProcessingException {
		String json = "{\"name\":\"Coder Sathi\",\"age\":30}";
		ObjectMapper objectMapper = new ObjectMapper();
		Person person = objectMapper.readValue(json, Person.class);
		System.out.println(person.getName()); // Output: Coder Sathi
		System.out.println(person.getAge()); // Output: 30
	}

	private static void convertJavaObjectToJSONString() throws JsonProcessingException {
		Person person = new Person("Coder Sathi", 30);
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonString = objectMapper.writeValueAsString(person);
		System.out.println(jsonString);
	}
}

Conclusion

In this post, we learn to convert Java Object to JSON String and vice versa using Jackson library. We also learn how to fix Cannot construct instance of error that comes during JSON String to Java Object conversion.

Sharing Is Caring: