Converting JSON message to Groovy Bean
The power of the Java/Groovy type system, reflection API, and other goodies may be very handy if you need to make more type-safe code.
JSON by definition is not doing any type checking, but it is possible to map the JSON data to the Java/Groovy objects to present data inside your application and get access to type information. And that's what we will demonstrate in this recipe.
Getting ready
First of all let's define a Groovy Bean (POGO) class, which holds data representing some vehicle information:
package org.groovy.cookbook import groovy.transform.ToString @ToString class Vehicle { static enum FuelType { DIESEL, PETROL, GAS, ELECTRIC } static enum TransmissionType { MANUAL, AUTOMATIC } @ToString static class Transmission { long gears TransmissionType type } String brand String model FuelType fuel Long releaseYear Transmission transmission }
As you can notice it's nothing, but a set of fields of simple types, enumerations...