Java ObjectNode-class And Method Code Example
Here is an example of using the ObjectNode class from the com.fasterxml.jackson.databind package in the Jackson library for Java:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class Main {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode person = mapper.createObjectNode();
person.put("name", "John");
person.put("age", 30);
person.put("address", "New York");
System.out.println(person.toString()); // prints {"name":"John","age":30,"address":"New York"}
}
}
In this example, we first import the ObjectMapper and ObjectNode classes from the com.fasterxml.jackson.databind package.
Then, we create a new instance of ObjectMapper and an empty ObjectNode by calling the createObjectNode() method and assigning it to the person variable.
We add key-value pairs to the person object using the put() method.
Finally, we print the string representation of person object by calling the toString() method, which returns the string representation of the json object {"name":"John","age":30,"address":"New York"}.
You can also use other methods from ObjectNode to add, remove or manipulate json elements in the object.
Also, you can use ObjectNode.get() method to get the value of a specific field in the json object and ObjectNode.path() method to get the value of a field by providing its path.
int age = person.get("age").asInt();
System.out.println(age); // prints 30
String address = person.path("address").asText();
System.out.println(address); // prints "New York"