Sunday, May 7, 2023

How to validate JSON in Java Jackson - Example Tutorial

Similar to XML, you can also validate a JSON. Even if you don't have a schema to validate JSON unlike XML, you can still check if the JSON string is properly formatted or not e.g. it confirms the JSON syntax or not. Any string satisfying JSON syntax standard is considered a valid JSON document. A Valid JSON is important because it ensures interoperation between application JSON related tools.  Although, there are a lot of web based JSON tools available which you help you to validate given JSON String they are only useful for one of usage like you got a JSON String and wondering if it is valid or not but if you are receiving JSON String programmatically from a web service, user or any other source, you definitely want to check if they are valid or not to avoid parsing errors like "Uncaught Syntax error: Unexpected Token"

Even though the Jackson API doesn't provide a valid method to validate JSON document you can always write your own utility method to perform validation by utilizing JSON parsing capability of Jackson library. 

If Jackson is able to parse a JSON document then it is a valid JSON, otherwise it's not. Alternatively, you can also use Postman tool to validate JSON using an external JSON Schema. 

How to validate JSON in Java Jackson - Example Tutorial



How to validate JSON String in Java? Jackson Example

Here is a simple way to confirm JSON syntax using Jackson library in a Java application. Unlike using tools, this is a programmatic way to check if JSON is valid or not. 

public boolean isValidJSON(final String json) {
  boolean valid = false;
  try {

  ObjectMapper objectMapper = ...;
  JsonNode jsonNode = objectMapper.readTree(yourJsonString);
  valid = true;

   } catch(JsonProcessingException e){
  e.printStackTrace();
}

Alternatively, you can also use following code using Jackson to check if JSON is valid or not:

public static boolean isValidJSON(final String json) throws IOException {
  boolean valid = true;
  try{ 
    objectMapper.readTree(json);
  } catch(JsonProcessingException e){
  valid = false;
  }
  return valid;
}


That's all about how to check if given JSON String is valid JSON or not. Though, for one of usages e.g. troubleshooting you can use web based tools to check if given JSON is valid or not. There are a lot of tool available in the web like JSONLint, a popular free JSON tool, where you can copy paste your JSON string and validate a JSON String, but if you have to perform validation programmatically like you are receiving JSON String from user or any other system then you should use a proper JSON library like Jackson to validated JSON document in Java.


No comments:

Post a Comment