Java Reference
In-Depth Information
<song id="...">
<title>...</title>
<artist>...</artist>
<year>...</year>
</song>
The method that converts a list of songs into a larger XML file just does the same thing for
each song.
Lessons learned (XML)
1. Groovy's
XmlParser
and
XmlSlurper
make parsing XML trivial, and values
can be extracted by walking the resulting DOM tree.
2. Generating XML is just as easy, using
MarkupBuilder
.
Groovy Sweet Spot
Groovy is excellent at parsing and generating XML. If your Java application works with
XML, strongly consider delegating to a Groovy module.
4.6. Working with JSON data
Groovy processes JSON data as easily as it processes XML. To conclude this chapter, let
me present a trivial example of JSON response data from a web service.
The service is known as ICNDB: the Internet Chuck Norris Database. It is located at
ht-
tp://icndb.com
and has a RESTful API for retrieving the associated jokes. If you send an
HTTP GET request to
http://api.icndb.com/jokes/random?limitTo=[nerdy]
you get back a
string in JSON form.
Groovy makes it easy to send a GET request. In the Groovy JDK the
String
class has
a
toURL
method, which converts it to an instance of
java.net.URL
. Then the Groovy
JDK adds a method to the URL class called
getText
. Accessing the web service is there-
fore as simple as