Java/Android - Validate String JSON against String schema

后端 未结 3 1417
谎友^
谎友^ 2020-12-13 07:54

I am having trouble finding the most simple way to validate a JSON String against a given JSON-schema String (for reference, this is in Java, running in an Android app).

3条回答
  •  情歌与酒
    2020-12-13 08:41

    This is essentially what the Servlet you linked to does, so it may not be a one-liner but it still is expressive.

    useV4 and useId as specified on the servlet, are for specifying validations option for Default to draft v4 and Use id for addressing.

    You can see it online: http://json-schema-validator.herokuapp.com/

    public boolean validate(String jsonData, String jsonSchema, boolean useV4, boolean useId) throws Exception {
       // create the Json nodes for schema and data
       JsonNode schemaNode = JsonLoader.fromString(jsonSchema); // throws JsonProcessingException if error
       JsonNode data = JsonLoader.fromString(jsonData);         // same here
    
       JsonSchemaFactory factory = JsonSchemaFactories.withOptions(useV4, useId);
       // load the schema and validate
       JsonSchema schema = factory.fromSchema(schemaNode);
       ValidationReport report = schema.validate(data);
    
       return report.isSuccess();
    }
    

提交回复
热议问题