How to Validate JSON with Jackson JSON

Not sure what your use case for this is, but this should do it:

public boolean isValidJSON(final String json) {
   boolean valid = false;
   try {
      final JsonParser parser = new ObjectMapper().getJsonFactory()
            .createJsonParser(json);
      while (parser.nextToken() != null) {
      }
      valid = true;
   } catch (JsonParseException jpe) {
      jpe.printStackTrace();
   } catch (IOException ioe) {
      ioe.printStackTrace();
   }

   return valid;
}

I would recommend using Bean Validation API separately: that is, first bind data to a POJO, then validate POJO. Data format level Schemas are in my opinion not very useful: one usually still has to validate higher level concerns, and schema languages themselves are clumsy, esp. ones that use format being validated (XML Schema and JSON Schema both have this basic flaw). Doing this makes code more modular, reusable, and separates concerns (serialization, data validation).

But I would actually go one step further, and suggest you have a look at DropWizard -- it integrates Jackson and Validation API implementation (from Hibernate project).


With Jackson I use this function:

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

Although Perception's answer probably will fit many needs, there are some problems it won't catch, one of them is duplicate keys, consider the following example:

String json = "{ \"foo\" : \"bar\", \"foo\" : \"baz\" }";

As a complement, you can check for duplicate keys with the following code:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
objectMapper.readTree(json);

It throws JsonProcessingException on duplicate key or other error.

Tags:

Java

Json

Jackson