如何处理JSON Key中的空格?

时间:2017-08-03 09:44:20

标签: json parsing groovy jsonslurper

我有一串JSON,我已经从API中检索过了。我使用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"的正确方法是什么,因为它有空格?

1 个答案:

答案 0 :(得分:2)

'包裹它:

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'
}