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

JSON Module Validation

 

Add a JSON Module – see how we can add a module in Anypoint Studio

JSON Module Validation

 

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

 

  
Thank you for taking out time to read the above post. Hope you found it useful. In case of any questions, feel free to comment below. Also, if you are keen on knowing about a specific topic, happy to explore your recommendations as well.
 
For any latest updates or posts on our website, you can follow us on LinkedIn. Look forward to connecting with you there.


Share this:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments