简体   繁体   中英

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM