Gokulnath Sekar Gokulnath Sekar - 2 months ago 13
JSON Question

Class 'JsonValidator' not found

https://github.com/hasbridge/php-json-schema

Getting error Class 'JsonValidator' not found.
I did install composer.json as in git folder.
I did put my json schema, json data files in src/Json and created a php file to validate as mentioned in git.
getting error class Class 'JsonValidator' not found.

Answer

In their example, they're creating a JsonValidator object.

This is different from the actual namespace of the class, which is Json\Validator.

Try dropping use Json\Validator as JsonValidator at the top of your file so that you're able to refer to the class the same way the docs do.

I'd expand their docs from:

$someJson = '{"foo":"bar"}';
$jsonObject = json_decode($someJson);

$validator = new JsonValidator('/path/to/yourschema.json');

$validator->validate($jsonObject);

To

<?php

namespace Your\Domain;

use Json\Validator as JsonValidator;

require_once('./vendor/autoload.php');

$someJson   = '{"foo": "bar"}';
$jsonObject = json_decode($someJson);
$validator  = new JsonValidator('/path/to/yourschema.json');

$validator->validate($jsonObject);

Alternatively, you could substitute new JsonValidator('/path/to/yourschema.json') for new Json\Validator('/path/to/yourschema.json').

Edit: By the way - you might find the example schemas at json-schema.org helpful when using this library.

Here's the main one from that link:

{
    "title": "Example Schema",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}

Save this file somewhere in your project and refer to it instead of /path/to/yourschema.json.