How do I use Groovy Maps and Lists with Web Services?
When passing and receiving structured data from a web service, a Groovy map represents an object and its properties.
For example, an Employee object with properties Empno
,
Ename
, Sal
, and Hiredate
is
represented by a Map object with four key/value pairs, where the names of the properties
are the keys.
The following example shows how you can create and use a Groovy map.
//You can create an empty Map using the syntax:
def newEmp =[:]
//Then, you can add properties to the map using the explicit put() method like this
newEmp.put("Empno",1234)
newEmp.put("Ename","Sean")
newEmp.put("Sal",9876)
newEmp.put("Hiredate",date(2013,8,11))
//Alternatively, you can assign and/or update map key/value pairs using a simpler direct assignment notation like this:
newEmp.Empno = 1234
newEmp.Ename = "Sean"
newEmp.Sal = 9876
newEmp.Hiredate = date(2013,8,11)
//You can also create a new map and assign some or all of its properties at once using the constructor syntax:
def newEmp1 = [Empno : 1234,
Ename : "Sean",
Sal : 9876,
Hiredate : date(2013,8,11)]
//To create a collection of objects you use the Groovy List object.
//You can create one object at a time and then create an empty list, and call the list's add() method to add both objects to the list:
def dependent1 = [Name : "Dave",
BirthYear : 1996]
def dependent2 = [Name : "Jenna",
BirthYear : 1999]
def listOfDependents = []
listOfDependents.add(dependent1)
listOfDependents.add(dependent2)
//To save a few steps, the last three lines above can be done in a single line by constructing a new list
//with the two desired elements in one line like this:
def listOfDependents1 = [dependent1, dependent2]
//Note that you can also construct a new employee with nested dependents all in one statement by further nesting the constructor syntax:
def newEmp2 = [Empno : 1234,
Ename : "Sean",
Sal : 9876,
Hiredate : date(2013,8,11),
Dependents : [
[Name : "Dave",
BirthYear : 1996],
[Name : "Jenna",
BirthYear : 1999]]
]