乐闻世界logo
搜索文章和话题

What is the difference between ObjectNode and JsonNode in Jackson?

1个答案

1

In the Jackson library, JsonNode is an abstract class representing immutable JSON nodes. ObjectNode is a subclass of JsonNode that represents JSON object nodes and offers various methods for adding, updating, or deleting child nodes.

Key Differences:

  1. Type and Mutability:

    • JsonNode: It is an abstract class used to represent all types of JSON nodes (e.g., objects, arrays, strings, numbers). JsonNode is immutable, meaning once created, its content cannot be changed.
    • ObjectNode: It is a concrete implementation of JsonNode specifically for representing JSON objects (a collection of key-value pairs). Unlike JsonNode, ObjectNode is mutable, allowing you to modify its content by adding, removing, or changing properties.
  2. Purpose and Functionality:

    • JsonNode: As a generic node, it is suitable for reading and querying JSON data but not for modifying data. You can use it to access and inspect data, but it cannot be directly modified.
    • ObjectNode: Because it is mutable, it is ideal for building or modifying JSON objects when needed. For example, if you need to dynamically construct a JSON response in your program, ObjectNode provides convenient methods such as put (to add or replace fields) and remove (to remove fields).

Example:

Suppose we have a JSON object as follows and need to perform some operations:

json
{ "name": "John Doe", "age": 30 }

If we want to read this data, JsonNode is sufficient:

java
JsonNode node = objectMapper.readTree(jsonString); String name = node.get("name").asText(); int age = node.get("age").asInt();

But if we need to modify this JSON, such as adding a new field, we need to use ObjectNode:

java
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(jsonString); objectNode.put("email", "john.doe@example.com"); // Now objectNode contains a new "email" field

In summary, you can choose between JsonNode and ObjectNode based on your usage requirements for JSON data (read-only access versus modification).

2024年8月9日 02:38 回复

你的答案