Skip to content
Advertisement

How to load JSON Schema file from java

My Project is a maven project and inside resources folder – src/main/resources folder I have a json schema file – “jsonschema.json “

package : src/main/resources
file : jsonschema.json

Now i want to validate my jsonobject with json schema

How to load the schema.json file in to the code :

Is the below line correct?

JsonNode schema = JsonLoader.fromResource("/jsonschema.json");  // correct? or correct me
JsonNode data = JsonLoader.fromString(jsonData);
ProcessingReport report = validator.validate(schema, data);

Advertisement

Answer

This may help you
Place jsonschema file on project root directory or in resource and read schema using normal file read and store it in variable say str

     booleab isValidRequest=false;
     String     requestData; // data to validate
     String str; //schema 

            JsonNode requestDataJsonNode = com.github.fge.jackson.JsonLoader.fromString(requestData);       
            final JsonNode schemaNode = JsonLoader.fromString(str);
           final JsonNode schemaNode=JsonLoader.fromResource("/jsonschema.json"); // for your query
            final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
            JsonValidator validator = factory.getValidator();        
            ProcessingReport processingReport=  validator.validate(schemaNode, requestDataJsonNode); 
            if(processingReport!=null)
            {
                isValidRequest=processingReport.isSuccess();
            }
            
            } catch (Exception e) {
                
            }

If You are getting exception while executing the program. add dependencies listed in below [link]

http://mvnrepository.com/artifact/com.github.fge/json-schema-validator/2.2.5

Advertisement