Chapter 57. Make Your Java Groovier
Ken Kousen
The screen was the color of a cyberpunk novel opened to the first line. I stared at it, worried I would never finish tonight. There was a knock on the wall of my cubicle. My boss stood there, waiting.
“How’s it going?” she said.
“Java is so verbose,” I sighed. “I just want to download some data from a service and save it to a database. I’m swimming in builders, factories, library code, try/catch blocks…”
“Just add Groovy.”
“Huh? How would that help?”
She sat down. “Mind if I drive?”
“Please.”
“Let me give you a quick demo.” She opened a command prompt and typed groovyConsole. A simple GUI appeared on the screen. “Say you want to know how many astronauts are in space at the moment. There’s a service at Open Notify that gives you that.”
She executed the following in the Groovy console:
def jsonTxt = 'http://api.open-notify.org/astros.json'.toURL().text
The JSON response came back with the number of astronauts, a status message, and nested objects relating each astronaut to a craft.
“Groovy adds toURL to String to generate a java.net.URL, and getText to URL to retrieve the data, which you access as text.”
“Sweet,” I said. “Now I have to map that to Java classes and use a library like Gson or Jackson—”
“Nah. If all you want is the number of people in space, just use a JsonSlurper.”
“A what?”
She typed:
def number = new JsonSlurper().parseText(jsonTxt).number ...