JAVA HELP

Jackson Java (How It Works For Developers)

Published September 29, 2024
Share:

In the realm of modern programming, handling data in the form of JSON (JavaScript Object Notation) has become a crucial task. JSON's simplicity and ease of use make it a popular choice for data interchange between a server and a client. For Java developers, the Jackson library stands out as a powerful tool for JSON processing. This article delves into the features, usage, and advantages of Jackson Java, providing code examples to illustrate its capabilities. Additionally, we'll explore IronPDF for Java and demonstrate how to integrate it with Jackson to generate PDF documents from JSON data.

What is Jackson?

Jackson is a high-performance JSON processor for Java. It provides comprehensive support for JSON, offering a suite of tools to serialize Java objects into JSON and deserialize JSON into Java objects. Developed by FasterXML, Jackson is widely used in the Java community due to its robustness, flexibility, and ease of use.

Core Features of Jackson

  1. Data Binding: Jackson excels at converting Java objects to JSON and vice versa, making it straightforward to serialize and deserialize data.
  2. Tree Model: This feature allows parsing JSON into a tree-like structure, enabling manipulation of JSON data without needing to bind it to specific Java objects.
  3. Streaming API: For processing large JSON files, Jackson provides a low-level API that reads and writes JSON content as discrete tokens.
  4. Annotations Support: Jackson supports various annotations to control the serialization and deserialization processes, providing fine-grained control over JSON processing.

    1. Extensibility: With modules for various data formats and additional functionality, Jackson is highly extensible.

Jackson Java (How It Works For Developers): Figure 1

Getting Started with Jackson

To begin using Jackson in your Java project, you need to add the necessary dependencies. For users using Maven, add the following code to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.2</version>
</dependency>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<dependency> <groupId> com.fasterxml.jackson.core</groupId> <artifactId> jackson-databind</artifactId> <version>2.13.2</version> </dependency>
VB   C#

Basic Usage of Jackson

1. Data Binding

The most common use of Jackson is to bind JSON data to Java objects (POJOs) and vice versa. Here's a straightforward example to demonstrate this:

import com.fasterxml.jackson.databind.ObjectMapper;
class Main {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        // Java object to JSON
        try {
            User user = new User("John", "Doe", 30);
            String jsonString = objectMapper.writeValueAsString(user);
            System.out.println("JSON String: " + jsonString);
            // JSON to Java object
            String jsonInput = "{\"firstName\":\"Jane\",\"lastName\":\"Doe\",\"age\":25}";
            User userFromJson = objectMapper.readValue(jsonInput, User.class);
            System.out.println("User from JSON: " + userFromJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class User {
    public String firstName;
    public String lastName;
    public int age;
    public User() {
    }
    public User(String firstname, String lastname, int i) {
        firstName = firstname;
        lastName = lastname;
        age = i;
    }
}
import com.fasterxml.jackson.databind.ObjectMapper;
class Main {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        // Java object to JSON
        try {
            User user = new User("John", "Doe", 30);
            String jsonString = objectMapper.writeValueAsString(user);
            System.out.println("JSON String: " + jsonString);
            // JSON to Java object
            String jsonInput = "{\"firstName\":\"Jane\",\"lastName\":\"Doe\",\"age\":25}";
            User userFromJson = objectMapper.readValue(jsonInput, User.class);
            System.out.println("User from JSON: " + userFromJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class User {
    public String firstName;
    public String lastName;
    public int age;
    public User() {
    }
    public User(String firstname, String lastname, int i) {
        firstName = firstname;
        lastName = lastname;
        age = i;
    }
}
Private com As import
Friend Class Main
	Public Shared Sub main(ByVal args() As String)
		Dim objectMapper As New ObjectMapper()
		' Java object to JSON
		Try
			Dim user As New User("John", "Doe", 30)
			Dim jsonString As String = objectMapper.writeValueAsString(user)
			System.out.println("JSON String: " & jsonString)
			' JSON to Java object
			Dim jsonInput As String = "{""firstName"":""Jane"",""lastName"":""Doe"",""age"":25}"
			Dim userFromJson As User = objectMapper.readValue(jsonInput, User.class)
			System.out.println("User from JSON: " & userFromJson)
		Catch e As Exception
			e.printStackTrace()
		End Try
	End Sub
End Class
Friend Class User
	Public firstName As String
	Public lastName As String
	Public age As Integer
	Public Sub New()
	End Sub
	Public Sub New(ByVal firstname As String, ByVal lastname As String, ByVal i As Integer)
		Me.firstName = firstname
		Me.lastName = lastname
		age = i
	End Sub
End Class
VB   C#

Jackson Java (How It Works For Developers): Figure 2 - Example output binding JSON data to Java Objects

2. Tree Model

Jackson's tree model is useful for manipulating JSON data without needing to create Java classes. Here's an example:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
class TreeModelExample {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = "{\"name\":\"John\", \"age\":30}";
            // Parse JSON string into JsonNode
            JsonNode rootNode = objectMapper.readTree(jsonString);
            System.out.println("Name: " + rootNode.get("name").asText());
            System.out.println("Age: " + rootNode.get("age").asInt());
            // Modify the JSON
            ((ObjectNode) rootNode).put("age", 31);
            System.out.println("Modified JSON: " + rootNode.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
class TreeModelExample {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = "{\"name\":\"John\", \"age\":30}";
            // Parse JSON string into JsonNode
            JsonNode rootNode = objectMapper.readTree(jsonString);
            System.out.println("Name: " + rootNode.get("name").asText());
            System.out.println("Age: " + rootNode.get("age").asInt());
            // Modify the JSON
            ((ObjectNode) rootNode).put("age", 31);
            System.out.println("Modified JSON: " + rootNode.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Private com As import
Private com As import
Private com As import
Friend Class TreeModelExample
	Public Shared Sub main(ByVal args() As String)
		Dim objectMapper As New ObjectMapper()
		Try
			Dim jsonString As String = "{""name"":""John"", ""age"":30}"
			' Parse JSON string into JsonNode
			Dim rootNode As JsonNode = objectMapper.readTree(jsonString)
			System.out.println("Name: " & rootNode.get("name").asText())
			System.out.println("Age: " & rootNode.get("age").asInt())
			' Modify the JSON
			CType(rootNode, ObjectNode).put("age", 31)
			System.out.println("Modified JSON: " & rootNode.toString())
		Catch e As Exception
			e.printStackTrace()
		End Try
	End Sub
End Class
VB   C#

Jackson Java (How It Works For Developers): Figure 3 - Directly modifiying the JSON data without using Java Classes

3. Streaming API

For processing large JSON files, the streaming API is efficient:

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.File;
class StreamingAPIExample {
    public static void main(String[] args) {
        JsonFactory factory = new JsonFactory();
        try (JsonParser parser = factory.createParser(new File("large.json"))) {
            while (!parser.isClosed()) {
                JsonToken token = parser.nextToken();
                if (token == JsonToken.FIELD_NAME) {
                    String fieldName = parser.getCurrentName();
                    System.out.println("Field: " + fieldName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.File;
class StreamingAPIExample {
    public static void main(String[] args) {
        JsonFactory factory = new JsonFactory();
        try (JsonParser parser = factory.createParser(new File("large.json"))) {
            while (!parser.isClosed()) {
                JsonToken token = parser.nextToken();
                if (token == JsonToken.FIELD_NAME) {
                    String fieldName = parser.getCurrentName();
                    System.out.println("Field: " + fieldName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Private com As import
Private com As import
Private com As import
Private java As import
Friend Class StreamingAPIExample
	Public Shared Sub main(ByVal args() As String)
		Dim factory As New JsonFactory()
		Try
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'			(JsonParser parser = factory.createParser(New File("large.json")))
'		{
'			while (!parser.isClosed())
'			{
'				JsonToken token = parser.nextToken();
'				if (token == JsonToken.FIELD_NAME)
'				{
'					String fieldName = parser.getCurrentName();
'					System.out.println("Field: " + fieldName);
'				}
'			}
'		}
		Catch e As Exception
			e.printStackTrace()
		End Try
		End Try
	End Sub
VB   C#

Input JSON file

Jackson Java (How It Works For Developers): Figure 4 - Example input JSON data

Output Image

Jackson Java (How It Works For Developers): Figure 5 - Example output data fields after processing

Introducing IronPDF for Java

IronPDF is a comprehensive library for creating, editing, and rendering PDF documents in Java. It provides a simple API to generate PDFs from various sources, such as HTML, URLs, or existing documents. IronPDF is particularly useful when you need to create PDFs from JSON data processed by Jackson, for example, if a developer is creating a Spring Boot application that involves generating reports based on data, IronPDF can significantly streamline the workflow.

Jackson Java (How It Works For Developers): Figure 6 - IronPDF homepage:The Java PDF Library

Adding IronPDF to Your Project

To use IronPDF in your project, add the following dependency:

<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>2023.6.0</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>2023.6.0</version>
</dependency>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<dependency> <groupId> com.ironsoftware</groupId> <artifactId> ironpdf</artifactId> <version>2023.6.0</version> </dependency>
VB   C#

Integrating Jackson with IronPDF

Combining Jackson and IronPDF, we can create a powerful solution to generate PDF documents from JSON data. Below is a comprehensive example that reads JSON data, processes it with Jackson, and generates a PDF document using IronPDF.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.*;
import java.io.File;
import java.util.List;
class JacksonIronPDFExample {
    public static void main(String[] args) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // Read JSON from a file
            List<Person> persons = objectMapper.readValue(new File("persons.json"),
                    objectMapper.getTypeFactory().constructCollectionType(List.class, Person.class));
            // Generate HTML content from the JSON data
            StringBuilder htmlContent = new StringBuilder("<h1>Persons List</h1><table border='1'><tr><th>First Name</th><th>Last Name</th><th>Birth Date</th></tr>");
            for (Person person : persons) {
                htmlContent.append("<tr>")
                        .append("<td>").append(person.getFirstName()).append("</td>")
                        .append("<td>").append(person.getLastName()).append("</td>")
                        .append("<td>").append(person.getBirthDate()).append("</td>")
                        .append("</tr>");
            }
            htmlContent.append("</table>");
            // Create PDF from the HTML content
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlContent.toString());
            pdf.saveAs("persons.pdf");
            System.out.println("PDF created successfully from JSON data!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Person {
    private String firstName;
    private String lastName;
    private String birthDate;
    // Constructors, getters, and setters omitted for brevity
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getBirthDate() {
        return birthDate;
    }
    public void setBirthDate(String birthDate) {
        this.birthDate = birthDate;
    }
}
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.*;
import java.io.File;
import java.util.List;
class JacksonIronPDFExample {
    public static void main(String[] args) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // Read JSON from a file
            List<Person> persons = objectMapper.readValue(new File("persons.json"),
                    objectMapper.getTypeFactory().constructCollectionType(List.class, Person.class));
            // Generate HTML content from the JSON data
            StringBuilder htmlContent = new StringBuilder("<h1>Persons List</h1><table border='1'><tr><th>First Name</th><th>Last Name</th><th>Birth Date</th></tr>");
            for (Person person : persons) {
                htmlContent.append("<tr>")
                        .append("<td>").append(person.getFirstName()).append("</td>")
                        .append("<td>").append(person.getLastName()).append("</td>")
                        .append("<td>").append(person.getBirthDate()).append("</td>")
                        .append("</tr>");
            }
            htmlContent.append("</table>");
            // Create PDF from the HTML content
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlContent.toString());
            pdf.saveAs("persons.pdf");
            System.out.println("PDF created successfully from JSON data!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Person {
    private String firstName;
    private String lastName;
    private String birthDate;
    // Constructors, getters, and setters omitted for brevity
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getBirthDate() {
        return birthDate;
    }
    public void setBirthDate(String birthDate) {
        this.birthDate = birthDate;
    }
}
Private com As import
Private com As import
Private com As import
Private java As import
Private java As import
Friend Class JacksonIronPDFExample
	Public Shared Sub main(ByVal args() As String)
		Try
			Dim objectMapper As New ObjectMapper()
			' Read JSON from a file
			Dim persons As List(Of Person) = objectMapper.readValue(New File("persons.json"), objectMapper.getTypeFactory().constructCollectionType(List.class, Person.class))
			' Generate HTML content from the JSON data
			Dim htmlContent As New StringBuilder("<h1>Persons List</h1><table border='1'><tr><th>First Name</th><th>Last Name</th><th>Birth Date</th></tr>")
			Do
				htmlContent.append("<tr>").append("<td>").append(person.getFirstName()).append("</td>").append("<td>").append(person.getLastName()).append("</td>").append("<td>").append(person.getBirthDate()).append("</td>").append("</tr>")
			Loop
			htmlContent.append("</table>")
			' Create PDF from the HTML content
			Dim pdf As PdfDocument = PdfDocument.renderHtmlAsPdf(htmlContent.toString())
			pdf.saveAs("persons.pdf")
			System.out.println("PDF created successfully from JSON data!")
		Catch e As Exception
			e.printStackTrace()
		End Try
	End Sub
End Class
Friend Class Person
	Private firstName As String
	Private lastName As String
	Private birthDate As String
	' Constructors, getters, and setters omitted for brevity
	Public Function getFirstName() As String
		Return firstName
	End Function
	Public Sub setFirstName(ByVal firstName As String)
		Me.firstName = firstName
	End Sub
	Public Function getLastName() As String
		Return lastName
	End Function
	Public Sub setLastName(ByVal lastName As String)
		Me.lastName = lastName
	End Sub
	Public Function getBirthDate() As String
		Return birthDate
	End Function
	Public Sub setBirthDate(ByVal birthDate As String)
		Me.birthDate = birthDate
	End Sub
End Class
VB   C#

Input JSON File

Jackson Java (How It Works For Developers): Figure 7 - Example input JSON data

Output PDF File

Jackson Java (How It Works For Developers): Figure 8 - Output utilzing IronPDF to generate a table with Jackson converting the JSON data

Conclusion

Jackson is an indispensable tool for Java developers working with JSON data. Its versatility, performance, and ease of use make it a preferred choice for JSON processing. When combined with IronPDF, it becomes even more powerful, allowing developers to easily convert JSON data into well-formatted PDF documents. By integrating these two libraries, you can streamline your data processing and reporting workflows, creating dynamic and professional-looking PDFs with minimal effort. Java's ecosystem, including the Jackson databind project, constantly evolves with minor versions and major updates. To ensure that your project uses the latest tools, always check the central maven repository for the latest Jackson releases and version number updates.

To learn more about how to render HTML as PDF, visit the IronPDF overview. For more details on Jackson core and Jackson annotations, click on the external links and refer to the official Jackson documentation.

< PREVIOUS
Google HTTP Client Library for Java (How It Works For Developers)
NEXT >
Apache Commons Mathematics (How It Works For Developers)

Install with Maven

Version: 2024.9.1

<dependency>
  <groupId>com.ironsoftware</groupId>
  <artifactId>ironpdf</artifactId>
  <version>2024.9.1</version>
</dependency>

Ready to get started? Version: 2024.9 just released

Free Maven Download View Licenses >