Groovy/Grails中的JSON

Kiv*_*vus 6 grails groovy json

我正在尝试通过他们的JSON导出访问网站.

该URL为: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}"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我为方法运行单元测试时,我只是得到No such property: GET for class: ProjectController groovy.lang.MissingPropertyException: No such property: GET for class: ProjectController了我无法理解的内容.

Mat*_*ell 14

您的示例代码存在一些问题.首先,要以这种方式访问​​GET和JSON,您需要静态导入它们:

import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON
Run Code Online (Sandbox Code Playgroud)

这将使代码编译,但不能成功运行.您的url.path值需要前导'/'(如HTTPBuilder页面所示).更重要的是,从您引用的URL返回的JSON 与执行Google搜索的示例代码返回的结构完全不同.如果您将URL加载到CuriousConcept非常方便的JSON Formatter服务中,您将看到结构.这是显示一些JSON数据的代码:

println json.name
println json.id
json.fields.each {
  println it
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,HTTPBuilder版本0.5.0中存在与此代码相关的重大更改.正如RC-1发布公告所述,

HTTPBuilder类的URL属性已重命名为uri

因此,如果您在某个时刻移动到0.5.0,则需要使用uri.path而不是url.path


Sie*_*uer 11

如果您只想获取数据,可以用Grails这样做:

import grails.converters.*;

def url = new URL("http://neotest.dabbledb.com/publish/neotest/f820728c-4451-41f6-b346-8cba54e52c6f/projects.jsonp")
def response = JSON.parse(url.newReader()) // response is an instance of JSONObject (see Grails API docs)

println response.toString(3) // Pretty-printed output
response.each { key, value ->
    println "$key = $value"
}
Run Code Online (Sandbox Code Playgroud)

(只是一个简单的替代方案)