Groovy có 1 vài cách viết for như sau:
I. For truyền thống
Là cách viết fori truyền thống từ a –> b
def list = [1,2,5,7]
for (int i = 0; i < list.size(); i++) {
log.info("value of index {} is {}", i, list[i])
}
II. Dùng for-each
Viết kiểu này, bạn bắt buộc phải đi đến từng item trong list, bạn ko thể lấy được index (vị trí) của item đó trong list.
def list = [1,2,5,7]
list.each {value ->
log.info("value is {}", value)
}
II. Dùng for-each with index
Thật may mắn, groovy có method để bạn vừa for-each vừa lấy được index
def list = [1,2,5,7]
list.eachWithIndex { value,index ->
log.info("value of index {} is {}", index, value)
}
IV. Bài toán thực tế
Mình có 1 json dạng như sau:
{
"users": [
{
"status": "FAIL",
"reason": "invalid username"
},
{
"status": "SUCCESS",
"reason": "PASS"
},
{
"status": "FAIL",
"reason": "invalid address"
}
]
}Bây giờ, mình cần phải đọc response này và log ra user nào có status fail và lý do của việc fail đó.
Step 1: Đọc response rồi convert thành json, đã viết ở bài này.
import groovy.json.JsonSlurper def slurper = new JsonSlurper() def response = slurper.parseText(prev.getResponseDataAsString()) def users = response.users;
Step 2: duyệt từng phần tử của users.
- Cách 1: dùng for truyền thống
for (int i = 0; i < users.size(); i++) {
if (users[i].status == 'FAIL') {
log.info("User in index {} fail with reason '{}' ", i, users[i].reason)
}
}- Cách 2: dùng for-each with index
users.eachWithIndex {user, index ->
if (user.status != 'SUCCESS') {
log.info("User in index {} fail with reason '{}' ", index, user.reason)
}
}- Result:
