1

我有一个从 API 检索到的 JSON 字符串。我JsonSlurper用来将字符串解析为 JSON,但我不确定当键包含空格时如何处理。

JSON 的一个示例是:

{
   "total": 3,
   "page": 1,
   "totalPages": 1,
   "results": [{
      "person name": "John Doe",
      "date of birth": "01/01/1990",
      "date of registration": "01/01/2016",
      "notes": "default user",
    }]
 }

我想遍历返回的结果并通过person name. 到目前为止,我怀疑会起作用的代码是:

final RestBuilder rest = new RestBuilder()
JsonSlurper slurper = new JsonSlurper()
def response = rest.get("http://example.com/api/getPeople")
def json = slurper.parseText(response.text)
def jsonResults = json.results
jsonResults.each { res ->
   assert res.personName == 'John Doe'
}

"person name"既然它有空格,那么正确的获取方法是什么?

4

1 回答 1

3

'

import groovy.json.JsonSlurper

def input = '''{
   "total": 3,
   "page": 1,
   "totalPages": 1,
   "results": [{
      "person name": "John Doe",
      "date of birth": "01/01/1990",
      "date of registration": "01/01/2016",
      "notes": "default user",
   }]
}'''

def json = new JsonSlurper().parseText(input)

json.results.each { res ->
   assert res.'person name' == 'John Doe'
}
于 2017-08-03T09:49:34.600 回答