WebサービスでのGroovyマップおよびリストの使用
webサービスから構造化データを渡して受信する場合、Groovyマップはオブジェクトとそのプロパティを表します。
たとえば、Empno
, Ename
, Sal
およびHiredate
プロパティを持つEmployeeオブジェクトは、4つのキー/バリュー・ペアを持つMapオブジェクトで表されます。プロパティの名前はキーです。 次の例は、Groovyマップを作成および使用する方法を示しています。
//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]]
]