diff --git a/json/pom.xml b/json/pom.xml new file mode 100644 index 0000000000..47f1f25aa2 --- /dev/null +++ b/json/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + org.baeldung + json + 0.0.1-SNAPSHOT + + + + + org.everit.json + org.everit.json.schema + 1.3.0 + + + + junit + junit + 4.12 + test + + + + + diff --git a/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java b/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java new file mode 100644 index 0000000000..273fd48bac --- /dev/null +++ b/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java @@ -0,0 +1,31 @@ +package org.baeldung.json.schema; + +import org.everit.json.schema.Schema; +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 givenInvalidInput_whenValidating_thenInvalid() { + + JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); + JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_invalid.json"))); + + Schema schema = SchemaLoader.load(jsonSchema); + schema.validate(jsonSubject); + } + + @Test + public void givenValidInput_whenValidating_thenValid() { + + JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); + JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_valid.json"))); + + Schema schema = SchemaLoader.load(jsonSchema); + schema.validate(jsonSubject); + } +} diff --git a/json/src/test/resources/product_invalid.json b/json/src/test/resources/product_invalid.json new file mode 100644 index 0000000000..7c55d8c7a5 --- /dev/null +++ b/json/src/test/resources/product_invalid.json @@ -0,0 +1,5 @@ +{ + "id": 1, + "name": "Lampshade", + "price": 0 +} diff --git a/json/src/test/resources/product_valid.json b/json/src/test/resources/product_valid.json new file mode 100644 index 0000000000..e0697dc4c2 --- /dev/null +++ b/json/src/test/resources/product_valid.json @@ -0,0 +1,5 @@ +{ + "id": 1, + "name": "Lampshade", + "price": 10 +} diff --git a/json/src/test/resources/schema.json b/json/src/test/resources/schema.json new file mode 100644 index 0000000000..7cf99d76e0 --- /dev/null +++ b/json/src/test/resources/schema.json @@ -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"] +}