In modern software development, JSON (JavaScript Object Notation) has become the de facto standard for data exchange. To work with JSON in Java, Jackson API is one of the most widely used libraries due to its simplicity and powerful features. In this blog post, we’ll explore how to create a nested JSON object using Plain Old Java Objects (POJO) with the Jackson API.
Prerequisites
Before we dive into coding, ensure that you have the following:
- Java Development Kit (JDK) installed.
- Jackson Library included in your project:
- Add the following Maven dependency to your
pom.xml
if you're using Maven:
What Is a Nested JSON Object?
A nested JSON object is a JSON structure where one or more JSON objects are embedded inside another JSON object. Here's an example:
{
"employee": {
"id": 101,
"name": "John Doe",
"contact": {
"email": "john.doe@example.com",
"phone": "123-456-7890"
},
"address": {
"city": "New York",
"zipCode": "10001"
}
}
}
This JSON represents an employee object with nested objects for contact and address.
Step-by-Step Guide to Creating Nested JSON Using POJO and Jackson
1. Define the POJOs
First, create Java classes that mirror the structure of your JSON. Each nested JSON object corresponds to a class.
Employee.java
2. Populate POJOs with Data
Once the POJOs are ready, you can populate them with data:
public class Main {
public static void main(String[] args) {
// Create Address object
Address address = new Address();
address.setCity("New York");
address.setZipCode("10001");
// Create Contact object
Contact contact = new Contact();
contact.setEmail("john.doe@example.com");
contact.setPhone("123-456-7890");
// Create Employee object and set nested objects
Employee employee = new Employee();
employee.setId(101);
employee.setName("John Doe");
employee.setContact(contact);
employee.setAddress(address);
// Convert POJO to JSON
try {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. Output
Running the above code will generate the following JSON:
{
"id": 101,
"name": "John Doe",
"contact": {
"email": "john.doe@example.com",
"phone": "123-456-7890"
},
"address": {
"city": "New York",
"zipCode": "10001"
}
}
Key Points to Remember
- POJO Structure: Ensure your POJOs reflect the JSON hierarchy.
- Jackson ObjectMapper: Use
ObjectMapper
to convert between POJOs and JSON. - Pretty Printing: Use
writerWithDefaultPrettyPrinter()
for readable JSON output. - Exception Handling: Always handle exceptions when working with JSON serialization.