Code Examples - Gnof/JsonValidator GitHub Wiki
Here are some examples of how to use the JsonValidator library:
// Import the library
import com.gnof.core.JsonValidator;
A Basic Validation
// JSON Validation Object
// We're validating that the attribute 'foo' exists in targetJson
String basicValidationJson = "{attribute: foo}";
// Target JSON to Validate
String targetJson = "{foo:bar, foo:bat}"
// Instantiate JsonValidation Object
JsonValidator validator = new JsonValidator();
// validate returns a boolean of whether the validation passed
boolean result = validator.validate(basicValidationJson, targetJson);
System.out.println(result);
>> true
Retrieving (all) the values for a specific tag:
// We can place the value we expect, and the validation will pass
// however, if we don't know or care what to expect, we can put a dummy value.
// the validation will "fail", but we will still have the values accessible in
// the Validation Result details under 'value-found'.
String retrievalValidation = "{attribute: foo, value: bar}"
// Target JSON to Validate
String targetJson = "{foo:bar, foo:bat}"
// Instantiate JsonValidation Object
JsonValidator validator = new JsonValidator();
// validate returns a boolean of whether the validation passed
boolean result = validator.validate(retrievalValidation , targetJson);
System.out.println(result);
>> true
// We're gonna turn our validation JSON into a JsonObject so we can use it as a key to look up our
// validation details
JsonParser parser = new JsonParser();
JsonObject validationKey = (JsonObject) parser.parse(retrievalValidation);