leadpony / justify

Justify is a JSON validator based on JSON Schema Specification and Jakarta JSON Processing API (JSON-P).
Apache License 2.0
96 stars 18 forks source link

Couple of basic questions #30

Closed ghost closed 5 years ago

ghost commented 5 years ago

Hi.

  1. It's not possible to pass json and schema as strings, I have to use something like this?
InputStream stream= new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8));
JsonSchema jsonSchema = service.readSchema(stream, StandardCharsets.UTF_8);
  1. How to get boolean as a result, true or false if json is valid or not?

  2. How to return list of problems from my method where validation is performed?

leadpony commented 5 years ago

Hi @nik0la-vr The following method returns whether the given JSON is valid or not as a boolean value. Both the JSON and the JSON schema are specified as string type.

    private static JsonValidationService service = JsonValidationService.newInstance();

    public static boolean validateJson(String schemaAsString, String jsonAsString) {
        JsonSchema schema = service.readSchema(new StringReader(schemaAsString));
        List<Problem> problems = new ArrayList<>();
        ProblemHandler handler = ProblemHandler.collectingTo(problems);
        try (JsonReader reader = service.createReader(new StringReader(jsonAsString), schema, handler)) {
            reader.readValue();
        }
        return problems.isEmpty();
    }

In Java, you can pass an instance of StringReader to any method accepting Reader. I believe you can easily modify the code above to return the list of problems found in the validation.

ghost commented 5 years ago

Thanks.