
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: June 28, 2023
This quick tutorial will show how to use Jackson 2 to convert a JSON String to a JsonNode (com.fasterxml.jackson.databind.JsonNode).
If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.
Very simply, to parse the JSON String we only need an ObjectMapper:
@Test
public void whenParsingJsonStringIntoJsonNode_thenCorrect()
throws JsonParseException, IOException {
String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
assertNotNull(actualObj);
}
If, for some reason, you need to go lower level than that, the following example exposes the JsonParser responsible with the actual parsing of the String:
@Test
public void givenUsingLowLevelApi_whenParsingJsonStringIntoJsonNode_thenCorrect()
throws JsonParseException, IOException {
String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(jsonString);
JsonNode actualObj = mapper.readTree(parser);
assertNotNull(actualObj);
}
After the JSON is parsed into a JsonNode Object, we can work with the Jackson JSON Tree Model:
@Test
public void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect()
throws JsonParseException, IOException {
String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
// When
JsonNode jsonNode1 = actualObj.get("k1");
assertThat(jsonNode1.textValue(), equalTo("v1"));
}
This article illustrated how to parse JSON Strings into the Jackson JsonNode model to enable a structured processing of the JSON Object.