如何检查键值嵌套列表中的值?

How can I check the value in a key-value nested list?

我已经创建了一个 REST 网络服务。

我在响应中有一个嵌套列表,每个列表中有 5 个键值关联。 我只想检查每个值的格式是否正确(布尔值、字符串或整数)。

这是嵌套列表。

{"marches": [
      {
      "id": 13,
      "libelle": "CAS",
      "libelleSite": "USA",
      "siteId": 1,
      "right": false,
      "active": true
   },
      {
      "id": 21,
      "libelle": "MQS",
      "libelleSite": "Spain",
      "siteId": 1,
      "right": false,
      "active": true
   },
      {
      "id": 1,
      "libelle": "ASCV",
      "libelleSite": "Italy",
      "siteId": 1,
      "right": false,
      "active": true
   }]
}

我使用 JsonSlurper class 读取 groovy 响应。

import groovy.json.JsonSlurper
def responseMessage = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(responseMessage)

通过以下循环,我实现了获取列表的每个块。

marches.each { n ->
    log.info "Nested $n \n"
}

例如,我想检查与键 "id"、“13”关联的值是否是整数等等。

你快到了。在.each里面,it表示嵌套对象:

json.marches.each { 
  assert it.id instanceof Integer  // one way to do it

  //another way
  if( !(it.libelle instanceof String) ){
    log.info "${it.id} has bad libelle"
  } 

  //one more way
  return (it.libelleSite instanceof String) &&
     (it.siteId instanceof Integer) && (it.right instanceof Boolean)
}

如果你不关心具体细节,只想确保它们都很好,你也可以使用.every

assert json.marches.every {
    it.id instanceof Integer &&
    it.libelle instanceof String &&
    it.libelleSite instanceof String &&
    it.active instanceof Boolean  //...and so on
}