Search code examples
javajsonvalidationgithubjson-schema-validator

java json schema validation relative path not working (URI not found)


I am looking at the 2.2.6 version of the validator code from github. I have not changed any code from the repo "https://github.com/fge/json-schema-validator.git"

I am unable to get example 1 running when i test it against my json schema that references a second schema file (I can get it working when I resort to a hardcoded URI).

I have simply repointed the "com.github.fge.jsonschema.examples.Example1.java" to use my teams json schema and json files. I have built the project and copied my json schema files into "json-schema-validator\bin\com\github\fge\jsonschema\examples" (All in the same folder, similar to fstab examples)

A section of the top level is attached,

               },
                "MovingWindow": {
                    "description": "Is this an moving window measure?",
                    "type": "boolean"
                }
            },
            "minItems": 1,
            "uniqueItems": true
        },
        "RealTimeProfile": {
            "$ref": "rtp.json#"
        }
    },
    "required": [
        "MeasureTemplateId",
        "MeasureInstanceId",

but I am unable to get the reading of the lower level, 2nd schema file ("rtp.json") to be recognised & work correctly. I am seeing the below error:

Exception in thread "main" com.github.fge.jsonschema.core.exceptions.ProcessingException: fatal: URI "rtp.json#" is not absolute level: "fatal" uri: "rtp.json#"

Snippet of my code:

File jsonFile = new File("CumulativeCountBad.json");
File jsonSchemaFile = new File("main.json");


JsonNode good = JsonLoader.fromFile(jsonFile);
JsonNode mainSchema = JsonLoader.fromFile(jsonSchemaFile);

final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();

final JsonSchema schema = factory.getJsonSchema(mainSchema);

ProcessingReport report;

report = schema.validate(good);
System.out.println("good: " + report);

My issue seems similar to the following issue but i don't seem to be able to gett the thing running when i set the reference to: "$ref": "rtp.json#"

https://github.com/fge/json-schema-validator/issues/94

Any help appreciated. PS - I am a java newbie, apologies if there is something obvious that i have ommited Thanks


Solution

  • The problem is that you load the JSON then turn it into a schema. And your schema does not have an absolute URI in "id". So, it cannot work.

    You want to use an absolute URI to load them. Since you originally use a File (note, with Java 7+ you really want to use java.nio.file instead), you can obtain an absolute URI to it with:

    final File jsonSchemaFile = new File("main.json");
    final URI uri = jsonSchemaFile.toURI();
    

    You then load the schema with:

    final JsonSchema schema = factory.getJsonSchema(uri.toString());