Search code examples
javajsonjackson

How to Validate JSON with Jackson JSON


I am trying to use Jackson JSON take a string and determine if it is valid JSON. Can anyone suggest a code sample to use (Java)?


Solution

  • 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;
    }