JSON Module Validation
JSON Module Validation is used to validate JSON against the JSON schema. It show exact error with the JSON payload and accordingly we can notify the client about the incoming JSON error.
Let’s create a project in Anypoint Studio
Drag and drop listener
Add a JSON Module – see how we can add a module in Anypoint Studio
Add a JSON schema in resource folder against which we want to validate the JSON
json-schema.json:
{ "$id": "https://example.com/arrays.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "description": "A representation of a person, company, organization, or place", "type": "object", "properties": { "fruits": { "type": "array", "items": { "type": "string" } }, "vegetables": { "type": "array", "items": { "$ref": "#/definitions/veggie" } } }, "definitions": { "veggie": { "type": "object", "required": [ "veggieName", "veggieLike" ], "properties": { "veggieName": { "type": "string", "description": "The name of the vegetable." }, "veggieLike": { "type": "boolean", "description": "Do I like this vegetable?" } } } } }
Drag and drop validation activity
Add Error on Continue block and add transformation in it
Transformation logic:
%dw 2.0 output application/json --- error.muleMessage.payload filter($.level == "error") map { "Error $$": { element: $.instance.pointer, message: $.message } }
Run the application and test it using SOAP UI
JSON payload:
{ "fruits": [ "apple", "orange", "pear" ], "vegetables": [ { "veggieName": 1234, "veggieLike": true }, { "veggieName": "broccoli", "veggieLike": "false" } ] }
Error Response:
[ { "Error 0": { "element": "/vegetables/0/veggieName", "message": "instance type (integer) does not match any allowed primitive type (allowed: [\"string\"])" } }, { "Error 1": { "element": "/vegetables/1/veggieLike", "message": "instance type (string) does not match any allowed primitive type (allowed: [\"boolean\"])" } } ]
Sample Application: json-validation-service
SOAP UI project: JSON-Validation-soapui-project
how to valide the fist field in the payload and print the first error occured