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:

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

Converting a JsonNode object back to a JSON string is 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 me on Twitter and LinkedIn. You can also subscribe to RSS Feed.