I'm trying to access a site via their JSON export.
The URL is: http://neotest.dabbledb.com/publish/neotest/f820728c-4451-41f6-b346-8cba54e52c6f/projects.jsonp
I'm using HTTPBuilder to try and accomplish this in Groovy, but am having trouble. I used the example code from http://groovy.codehaus.org/HTTP+Builder to come up with this:
// 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}"
}
}
}
However, when I run the unit test for the method I simply get No such property: GET for class: ProjectController groovy.lang.MissingPropertyException: No such property: GET for class: ProjectController
which I'm having trouble understanding.
JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others.
There are a few problems with your sample code. First of all, to access GET and JSON that way, you need to statically import them:
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON
That will make the code compile, but not run successfully. Your url.path value needs a leading '/' (as shown on the HTTPBuilder page). More importantly, the JSON that comes back from the URL you're referencing has a totally different structure from that returned by the example code that performs a Google search. If you load your URL into the very handy JSON Formatter service at CuriousConcept, you'll see the structure. Here's code that would display some of the JSON data:
println json.name
println json.id
json.fields.each {
println it
}
By the way, there's a breaking change in version 0.5.0 of HTTPBuilder that is relevant to this code. As the RC-1 release announcement states,
The HTTPBuilder class' URL property has been renamed to uri
So, if you move to 0.5.0 at some point, you'll need to use uri.path instead of url.path
If you just want to fetch the data, you could do it in Grails this way:
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"
}
(just as a simple alternative)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With