JSONValidator { public static void validate(String json, InputStream inputStream) throws JSONValidatorException { if (Validator.isNull(json)) { return; } try { JSONObject jsonSchemaJSONObject = new JSONObject( new JSONTokener(inputStream)); Schema schema = SchemaLoader.load(jsonSchemaJSONObject); JSONObject jsonObject = new JSONObject(json); schema.validate(jsonObject); } catch (Exception exception) { if (exception instanceof JSONException) { JSONException jsonException = (JSONException)exception; throw new JSONValidatorException( jsonException.getMessage(), jsonException); } else if (exception instanceof ValidationException) { ValidationException validationException = (ValidationException)exception; String errorMessage = validationException.getErrorMessage(); List<String> messages = validationException.getAllMessages(); if (!messages.isEmpty()) { List<String> formattedMessages = new ArrayList<>(); messages.forEach( message -> { if (message.startsWith("#: ")) { message = message.substring(3); } else if (message.startsWith("#")) { message = message.substring(1); } formattedMessages.add(message); }); errorMessage = StringUtil.merge( formattedMessages, StringPool.NEW_LINE); } throw new JSONValidatorException(errorMessage, exception); } throw new JSONValidatorException(exception); } }  static void validate(String json, InputStream inputStream);  }
@Test public void testValidateExampleInvalidExtraProperties() throws Exception { expectedException.expect(JSONValidatorException.class); expectedException.expectMessage( new StringStartsWith("extraneous key [extra] is not permitted")); JSONValidator.validate( _read("example_invalid_extra_properties.json"), _readJSONSchemaAsStream()); }
@Test public void testValidateExampleInvalidRequiredPropertyMissing() throws Exception { expectedException.expect(JSONValidatorException.class); expectedException.expectMessage( new StringStartsWith("required key [example] not found")); JSONValidator.validate( _read("example_invalid_required_property_missing.json"), _readJSONSchemaAsStream()); }
@Test public void testValidateExampleValidRequired() throws Exception { JSONValidator.validate( _read("example_valid_required.json"), _readJSONSchemaAsStream()); }