我正在尝试通过 JSON 导出来访问网站。
网址是:http://neotest.dabbledb.com/publish/neotest/f820728c-4451-41f6-b346-8cba54e52c6f/projects.jsonp
我正在使用 HTTPBuilder 尝试在 Groovy 中完成此任务,但遇到了麻烦。我使用了 http://groovy.codehaus.org/HTTP+Builder 中的示例代码想出这个:
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
url.path = 'publish/neotest/f820728c-4451-41f6-b346-8cba54e52c6f/projects.jsonp'
// response handler for a success response code:
response.success = { resp, json ->
println resp.statusLine
// parse the JSON response object:
json.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
}
但是,当我对该方法运行单元测试时,我只是得到 No such property: GET for class: ProjectController groovy.lang.MissingPropertyException: No such property: GET for class: ProjectController
我无法理解。
最佳答案
您的示例代码存在一些问题。首先,要以这种方式访问 GET 和 JSON,您需要静态导入它们:
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON
这将使代码编译,但无法成功运行。您的 url.path 值需要一个前导“/”(如 HTTPBuilder page 所示)。更重要的是,从 the URL you're referencing 返回的 JSON其结构与执行 Google 搜索的示例代码返回的结构完全不同。如果您加载your URL进入非常方便JSON Formatter service at CuriousConcept ,你会看到结构。下面的代码将显示一些 JSON 数据:
println json.name
println json.id
json.fields.each {
println it
}
顺便说一句,version 0.5.0 of HTTPBuilder 中有一个重大变化。与此代码相关。正如 RC-1 发布公告所述,
The HTTPBuilder class' URL property has been renamed to uri
因此,如果您在某个时候迁移到 0.5.0,则需要使用 uri.path 而不是 url.path
关于Groovy/Grails 中的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1323758/