How to Check if JSON String is Valid in Java using Jackson


How can we validate a JSON string in Java using Jackson?

Suppose we have a static ObjectMapper available.

public static final ObjectMapper OBJECT_MAPPER;

Using readTree(), we can attempt to read the JSON content’s tree model, which is an in-memory tree representation of the JSON document.

If the readTree() function returns a JsonProcessingException, we can assume the JSON string is invalid.

public static boolean isJsonValid(String json) {
  try {
    JsonNode node = OBJECT_MAPPER.readTree(json);
    return node != null && !node.isMissingNode();
  } catch (JsonProcessingException e1) {
    return false;
  } catch (IOException e2) {
    throw new RuntimeException(e2);
  }
}

Otherwise, we have an IOException, and we’ll throw a standard RunTimeException.