Add JSON Schema validation
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package org.baeldung.json.schema;
|
||||
|
||||
import org.everit.json.schema.Schema;
|
||||
import org.everit.json.schema.ValidationException;
|
||||
import org.everit.json.schema.loader.SchemaLoader;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONTokener;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JSONSchemaTest {
|
||||
|
||||
@Test
|
||||
public void validateJSON() {
|
||||
|
||||
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json")));
|
||||
JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product.json")));
|
||||
|
||||
Schema schema = SchemaLoader.load(jsonSchema);
|
||||
|
||||
try {
|
||||
|
||||
schema.validate(jsonSubject);
|
||||
}
|
||||
|
||||
catch (ValidationException e) {
|
||||
|
||||
System.out.println(e.getMessage());
|
||||
e.getCausingExceptions().stream().map(ValidationException::getMessage).forEach(System.out::println);
|
||||
}
|
||||
}
|
||||
}
|
||||
5
json/src/test/resources/product.json
Normal file
5
json/src/test/resources/product.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Lampshade",
|
||||
"price": 0
|
||||
}
|
||||
22
json/src/test/resources/schema.json
Normal file
22
json/src/test/resources/schema.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"title": "Product",
|
||||
"description": "A product from the catalog",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "The unique identifier for a product",
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name of the product",
|
||||
"type": "string"
|
||||
},
|
||||
"price": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"exclusiveMinimum": true
|
||||
}
|
||||
},
|
||||
"required": ["id", "name", "price"]
|
||||
}
|
||||
Reference in New Issue
Block a user