While working on a Mule Application project, if you a planning to validate JSON payload against some JSON schema, and more importantly if you want to pass schema location dynamically, then this post will be beneficial for you.
Mule provides JSON Schema Validator as out of the box feature. From mule documentation, evaluates JSON payloads at runtime and verifies that they match a referenced JSON schema. You can match against schemas that exist in a local file or in an external URI. If the validation fails, an exception is raised with feedback about what went wrong and a reference to the original invalid payload.
Above code works but here is the catch, in my scenario, the schema location was dynamic. Let’s say the schema location is present in the database. Once the schema location value is retrieved from database, it is stored in a flow variable. For simplicity, I am creating a flow variable with hard-coded value. In actual application, the flow variable value will be the value retrieved from database.
Now, if I try to use JSON schema validator as shown below, then mule application throws error and application deployment fails. Basically, we cannot pass dynamic schema location value for “schemaLocation” attribute.
Here are the steps to resolve this issue and use dynamic schema location:
- Create custom processor class
- Retrieved schema location value from flow variable
- Create instance of Mule’s JSON Schema Validator class
- Invoke .validate operation
Bingo! I can now provide dynamic schema location for JSON schema validation. This is one simple way to dynamically provide JSON schema location when using JSON Schema Validator. Hope this helps.