Validating JSON messages
JSON is replacing XML for many applications, but one of the features that XML is exceptionally good for is the ability to validate XML content against a DTD or an XML Schema.
Due to the lightweight nature of JSON, it is quite simple to construct invalid or incomplete messages. That's why the necessity of JSON validation will arise quite soon if you plan to develop high-quality and error-free applications.
This recipe will list some ways to validate your JSON input with the help of Groovy.
Getting ready
For this recipe, we are going to use a simple JSON document representing a vehicle and some of its core attributes. Let's define a vehicle.json
file containing a JSON representation of a car:
{ "brand": "Mazda", "model": "5", "fuel": "PETROL", "releaseYear": 2007, "transmission": { "gears": "5", "type": "MANUAL" } }
How to do it...
Since JSON messages are represented by Map
s and List
s, you can just use the Groovy operators and collection methods—or simple...