简体   繁体   中英

Validate JSON against JSON schema (in Java)

I am using com.github.fge.jsonschema . Working in Java.

Following is the JSON Schema.

    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Employee",
    "description": "employee description",
    "type": "object",
    "properties": {
        "eid": {
            "description": "The unique identifier for a emp",
            "type": "integer"
        },
        "ename": {
            "description": "Name of the emp",
            "type": "string"
        },
        "qual":{
            "$ref": "#/definitions/qualification"   
        }
    },
    "definitions": {
        "qualification": 
        {
            "description": "Qualification",
            "type": "string"
        }
    }
}

and this is the JSON to validate against schema.

{
    "eid":1000,
    "ename": "mrun",
    "qualification": "BE"
}

The issue is that it is validating type (ie integer or string) properly for eid and ename, if we pass any wrong data. For eg:

{
    "eid":"Mrun", //should be Integer
    "ename": 72831287, //should be String
    "qualification": 98372489 //should be String
}

If we pass wrong type for qualification only then it validating as true (ie it does not validate the type for qualification maybe because it is nested).

Need to perform the validations for the whole JSON.

Is there any other solution to validate nested objects in JSON?

Thanks in advance.

Your example

{
    "eid":"Mrun",
    "ename": 72831287,
    "qualification": 98372489
}

does not match your schema. Your schema expects objects like

{
    "eid": "Mrun",
    "ename": 72831287,
    "qual": {
        "qualification": 98372489
    }
}

But if you just want to reuse the "qualification" definition, your schema should look similar to

"properties": {
    "eid": {
        "description": "The unique identifier for a emp",
        "type": "integer"
    },
    "ename": {
        "description": "Name of the emp",
        "type": "string"
    },
    "qualification":{
        "$ref": "#/definitions/qualification"   
    }
}

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