JAVA帮助

Jackson Java(它如何为开发人员工作)

发布 2024年九月29日
分享:

在现代编程领域中,处理以 JSON 形式的数据(JavaScript 对象符号)已经成为一项关键任务。 JSON 的简单性和易用性使其成为服务器和客户端之间数据交换的热门选择。 对于 Java 开发人员来说,Jackson 库是一个用于处理 JSON 的强大工具。 本文深入探讨了Jackson Java的功能、用法和优势,并提供代码示例来说明其功能。 另外,我们将探索IronPDF用于 Java,并演示如何将其与 Jackson 集成以从 JSON 数据生成 PDF 文档。

什么是Jackson?

Jackson是一个高性能的Java JSON处理器。 它为JSON提供全面支持,提供了一套工具将Java对象序列化为JSON并将JSON反序列化为Java对象。 由FasterXML开发的Jackson因其稳健性、灵活性和易用性在Java社区中被广泛使用。

Jackson的核心功能

  1. 数据绑定:Jackson 擅长在 Java 对象和 JSON 之间进行转换,使数据的序列化和反序列化变得简单明了。

  2. 树模型:此功能允许将JSON解析为树状结构,便于在不需要将其绑定到特定Java对象的情况下操作JSON数据。

  3. 流式API:为处理大型JSON文件,Jackson提供了一个低级API,它将JSON内容作为离散标记进行读写。

  4. 注解支持:Jackson 支持多种注解来控制序列化和反序列化过程,提供对 JSON 处理的精细控制。

    1. 可扩展性:通过支持各种数据格式和附加功能的模块,Jackson 的扩展性非常高。

    Jackson Java(对开发人员的工作原理):图 1

开始使用Jackson

要在您的Java项目中开始使用Jackson,您需要添加必要的依赖项。 对于使用 Maven 的用户,请在您的 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#

Jackson的基本用法

1. 数据绑定

Jackson最常见的用途是将JSON数据绑定到Java对象。(POJOs)反之亦然。 以下是一个简单的示例来说明这一点:

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(对开发者的工作原理):图2 - 将JSON数据绑定到Java对象的示例输出

2. 树模型

Jackson 的树模型在无需创建 Java 类的情况下,很适合处理 JSON 数据。 这里有一个例子:

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(对开发人员的工作原理):图 3 - 直接修改 JSON 数据而不使用 Java 类

3. 流式 API

对于处理大型 JSON 文件,流式 API 是高效的:

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#

输入JSON文件

Jackson Java(它如何为开发人员工作):图 4 - 示例输入 JSON 数据

输出图像

Jackson Java(对开发人员的工作原理):图5 - 处理后输出数据字段示例

介绍 IronPDF for Java

IronPDF是一个用于在Java中创建、编辑和渲染PDF文档的综合库。 它提供了一个简单的API,可以从各种来源生成PDF,例如HTML、URL或现有文档。 当需要从由Jackson处理的JSON数据创建PDF时,IronPDF特别有用。例如,如果开发人员正在创建一个涉及基于数据生成报告的Spring Boot应用程序,IronPDF可以显著简化工作流程。

Jackson Java(开发者工作原理):图6 - IronPDF主页:Java PDF库

将IronPDF添加到您的项目中

要在您的项目中使用IronPDF,请添加以下依赖项:

<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#

将 Jackson 与 IronPDF 集成

结合Jackson和IronPDF,我们可以创建一个强大的解决方案,以从JSON数据生成PDF文档。 下面是一个全面的示例,读取JSON数据,使用Jackson处理它,并使用IronPDF生成PDF文档。

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#

输入 JSON 文件

Jackson Java(它是如何为开发人员工作的):图 7 - 示例输入 JSON 数据

输出 PDF 文件

Jackson Java(对开发者的工作原理):图8 - 使用IronPDF生成一张表格,并用Jackson转换JSON数据的输出

结论

Jackson 是 Java 开发人员处理 JSON 数据的不可或缺的工具。 其多功能性、性能和易用性使其成为JSON处理的首选。 与IronPDF结合使用时,它变得更加强大,允许开发人员轻松将JSON数据转换为格式良好的PDF文档。 通过集成这两个库,您可以简化数据处理和报告工作流程,以最小的努力创建动态且专业外观的PDF。 Java 的生态系统,包括 Jackson databind 项目,随着次要版本和主要更新不断演进。 为确保您的项目使用最新工具,始终检查中央Maven仓库以获取Jackson的最新版本发布和版本号更新。

要了解更多关于如何将HTML渲染为PDF的信息,请访问IronPDF 概述. 有关 Jackson 核心和 Jackson 注释的更多详细信息,请单击外部链接并参考官方内容。Jackson 文档.

< 前一页
适用于Java的Google HTTP客户端库(开发者如何使用)
下一步 >
面向 Java 开发人员的 Apache Commons 数学

通过Maven安装

版本:2024.11.4

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

准备开始了吗? 版本: 2024.11 刚刚发布

免费 Maven 下载 查看许可证 >