Add JSON Schema validation

This commit is contained in:
Ivan Paolillo
2016-06-21 18:02:14 +02:00
parent 737848c9be
commit 3d0b89a66a
6 changed files with 139 additions and 0 deletions

View File

@@ -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);
}
}
}

View File

@@ -0,0 +1,5 @@
{
"id": 1,
"name": "Lampshade",
"price": 0
}

View 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"]
}