Java NodeSerialization-class And Method Code Example
Here is an example of using the ObjectMapper class from the com.fasterxml.jackson.databind package in the Jackson library for Java to serialize a JsonNode object:
import com.fasterxml.jackson.databind.JsonNode;
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 rootNode = mapper.createObjectNode();
rootNode.put("name", "John");
rootNode.put("age", 30);
rootNode.put("address", "New York");
try {
String json = mapper.writeValueAsString(rootNode);
System.out.println(json); // prints {"name":"John","age":30,"address":"New York"}
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example, we first import the JsonNode, 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.
We add key-value pairs to the rootNode object using the put() method.
Finally, we use the writeValueAsString() method from the ObjectMapper to convert the rootNode object to a json string and print the result.
You can also use other methods from ObjectMapper to serialize jsonNode to other formats like json file, jsonbyte[] and jsonStream.
And also you can use JsonNode.toString() instead of writeValueAsString() but it's less efficient.