Java Reference
In-Depth Information
String url = 'http://api.icndb.com/jokes/random?limitTo=[nerdy]'
String jsonTxt = url.toURL().text
println jsonTxt
Executing this returns a JSON object of the form
{ "type": "success", "value": { "id": 563, "joke": "Chuck Norris causes the
Windows Blue Screen of Death.", "categories": ["nerdy"] } }
In all the Google geocoder demonstrations I've used so far in this topic I introduced
the
XmlSlurper
class, whose
parse
method takes the URL in string form and auto-
matically converts the result to a DOM tree. Since version 1.8, Groovy also includes a
JsonSlurper
, but it doesn't have as many overloads of the
parse
method as the
Xm-
lSlurper
does. It does, however, contain a
parseText
method, which can process the
jsonTxt
returned from the previous code.
If I add that to the earlier lines, the complete ICNDB script is shown in the next listing.
Listing 4.11.
chuck_norris.groovy
, which processes data from ICNDB
import groovy.json.JsonSlurper
String url = 'http://api.icndb.com/jokes/random?limitTo=[nerdy]'
String jsonTxt = url.toURL().text
def json = new JsonSlurper().parseText(jsonTxt)
def joke = json?.value?.joke
println joke
The
parseText
method on
JsonSlurper
converts the JSON data into Groovy maps
and lists. I then access the
value
property of the
json
object, which is a contained JSON
object. It has a
joke
property, which contains the string I'm looking for.
The result of executing this script is something like this:
Chuck Norris can make a method abstract and final
Just as generating XML is done by scripting the output through a
MarkupBuilder
, gen-
erating JSON data uses the
groovy.json.JsonBuilder
class. See the GroovyDocs
for
JsonBuilder
for a complete example.