java - How to apply a sub schema in the JSON Schema validator? -
hi i'm using json schema evaluator in version 2.2.6 validate server responses. these responses can contain single objects of type a, b or c, composite objects, e.g., d containing array of objects. reuse schema definitions of each object, started describe entities in same file described here. problem is, have reference 1 of single objects when validating response.
here (not) swe.
json schema file:
{ "id":"#root", "properties": { "objecta": { "type": "object", "id":"#objecta", "properties": { "attribute1": {"type": "integer"}, "attribute2": {"type": "null"}, }, "required": ["attribute1", "attribute2"] }, "objectb": { "type": "object", "id":"#objectb", "properties": { "attribute1": {"type": "integer"}, "attribute2": { "type": "array", "items": { "$ref": "#/objecta" } } } }, "required": ["attribute1", "attribute2"] }, } } now want validate server response containing object b. this, tried following:
public class schemevalidator { public static void main(string[] args) { string jsondata = pseudocodefileload("exampleresponse/objectb.txt"); final file jsonschemafile = new file("resources/jsonschemes/completescheme.json"); final uri uri = jsonschemafile.touri(); processingreport report = null; try { jsonschemafactory factory = jsonschemafactory.bydefault(); final jsonschema schema = factory.getjsonschema(uri.tostring() + "#objectb"); jsonnode data = jsonloader.fromstring(jsondata); report = schema.validate(data); } catch (jsonparseexception jpex) { // ... handle parsing errors etc. } } } the problem scheme not loaded correctly. either no error (even invalid responses) or fatal: illegaljsonref scheme seems empty. how can use schema of object b in java code? thank you!!
it looks $ref incorrect. needs relative reference base of json schema file (see here).
so json schema become:
{ "id":"#root", "properties": { "objecta": { "type": "object", "id":"#objecta", "properties": { "attribute1": {"type": "integer"}, "attribute2": {"type": "null"}, }, "required": ["attribute1", "attribute2"] }, "objectb": { "type": "object", "id":"#objectb", "properties": { "attribute1": {"type": "integer"}, "attribute2": { "type": "array", "items": { "$ref": "#/properties/objecta" } } } }, "required": ["attribute1", "attribute2"] }, } }
i've added '/properties' $ref. it's operating xpath definition of object in schema file.
Comments
Post a Comment