In this short tutorial, you'll learn how to parse a JSON string to a JsonNode object and vice versa using the Jackson library.

Convert JSON String to JsonNode

To convert a JSON string to JsonNode, you can use the readTree() method from ObjectMapper. This method builds a tree model for all nodes and returns the root of the tree:

try {
    // JSON string
    String json = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"," +
            "\"roles\":[\"Member\",\"Admin\"],\"admin\":true,\"city\"" +
            ":\"New York City\",\"country\":\"United States\"}";

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON string to `JsonNode`
    JsonNode node = mapper.readTree(json);

    // print JSON nodes
    System.out.println(node.path("name").asText());
    System.out.println(node.path("email").asText());
    System.out.println(node.path("roles").get(0).asText());

} catch (Exception ex) {
    ex.printStackTrace();
}

Convert JSON File to JsonNode

If your JSON data is stored in an external file, you can still parse its content to JsonNode, as shown below:

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON file to `JsonNode`
    JsonNode node = mapper.readTree(Paths.get("user.json").toFile());

    // print JSON nodes
    System.out.println(node.path("name").asText());
    System.out.println(node.path("email").asText());
    System.out.println(node.path("roles").get(0).asText());

} catch (Exception ex) {
    ex.printStackTrace();
}

Convert JsonNode to JSON String

To convert a JsonNode object back to a JSON string is pretty straightforward. You can simply call the toString() method (or toPrettyString() for pretty print JSON) to get the JSON structure as a string:

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON file to `JsonNode`
    JsonNode node = mapper.readTree(Paths.get("user.json").toFile());

    // `JsonNode` to JSON string
    String json = node.toPrettyString();

    // print JSON string
    System.out.println(json);
    
} catch (Exception ex) {
    ex.printStackTrace();
}

The above code will print the following JSON on the console:

{
  "name" : "John Doe",
  "email" : "john.doe@example.com",
  "roles" : [ "Member", "Admin" ],
  "admin" : true,
  "city" : "New York City",
  "country" : "United States"
}

Read the guide Working with Tree Model Nodes in Jackson for more JsonNode examples.

For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.