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:
-
Type and Mutability:
- JsonNode: It is an abstract class used to represent all types of JSON nodes (e.g., objects, arrays, strings, numbers).
JsonNodeis immutable, meaning once created, its content cannot be changed. - ObjectNode: It is a concrete implementation of
JsonNodespecifically for representing JSON objects (a collection of key-value pairs). UnlikeJsonNode,ObjectNodeis mutable, allowing you to modify its content by adding, removing, or changing properties.
- JsonNode: It is an abstract class used to represent all types of JSON nodes (e.g., objects, arrays, strings, numbers).
-
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,
ObjectNodeprovides convenient methods such asput(to add or replace fields) andremove(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:
javaJsonNode 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:
javaObjectNode 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 回复