I have a restful web service(JAVA) which has to accept JSON requests. I have to first validate this JSON against a JSON schema that I have. I'm not sure what is the best JAVA library to validate JSON again JSON schemas. I have used json-schema-validator-2.1.7 library but it has not been very helpful. Even thought my JSON is not a valid JSON I do not get any errors.
Here is the code I use for json-schema-validator-2.1.7
InputStream jsonSchemaInputStream = Assessment.class.getClassLoader().getResourceAsStream("Schemas/AssessmentMetrics.json");
ObjectMapper mapper = new ObjectMapper();
// Allows to retrieve a JSONSchema object on various sources
// supported by the ObjectMapper provided
JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper);
// Retrieves a JSON Schema object based on a file
JSONSchema schema = schemaProvider.getSchema(jsonSchemaInputStream);
// Validates a JSON Instance object stored in a file
List<String> errors = schema.validate(contents);
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
JSON Schema validation asserts constraints on the structure of instance data. An instance location that satisfies all asserted constraints is then annotated with any keywords that contain non-assertion information, such as descriptive metadata and usage hints.
JSON Schema is a declarative language for validating the format and structure of a JSON Object. It allows us to specify the number of special primitives to describe exactly what a valid JSON Object will look like.
Here is a nice list.
Here is an online sandbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With