Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Kenneth A. Kousen - Making Java Groovy - 2014.pdf
Скачиваний:
47
Добавлен:
19.03.2016
Размер:
15.36 Mб
Скачать

Working with JSON data

89

4.6Working 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 http://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 therefore as simple as

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 book I introduced the XmlSlurper class, whose parse method takes the URL in string form and automatically 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 XmlSlurper 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, generating JSON data uses the groovy.json.JsonBuilder class. See the GroovyDocs for JsonBuilder for a complete example.

www.it-ebooks.info

90

CHAPTER 4 Using Groovy features in Java

Lessons learned (JSON)

1The JsonSlurper class has a parseText method for working with JSON formatted strings.

2The JsonBuilder class generates JSON strings using the same mechanism as the XmlSlurper.

This completes the tour of Groovy features that can be added to Java applications regardless of use case.

Lessons learned (Groovy features used in Java)

1When Groovy access a POJO it can use the map-based constructor as though it were a POGO.

2Every operator in Groovy delegates to a method, and if that method is implemented in a Java class the operator in Groovy will still use it. This means you can do operator overloading even in a Java class.

3The Groovy JDK documents all the methods that Groovy adds to the Java standard API through metaprogramming.

4Groovy AST transformations can only be applied to Groovy classes, but the classes can be mixed with Java in interesting ways. This chapter includes examples of @Delegate, @Immutable, and @Singleton.

4.7Summary

This chapter reviewed many ways that Groovy can help Java at the basic level, from POJO enhancements to AST transformations to building XML and more. I’ll use these techniques in future chapters wherever they can help. I’ll also review other helpful techniques along the way, though these are most of the major ones.

The next couple of chapters, however, change the focus. Although mixing Java and Groovy is easy and is a major theme of this book, some companies are reluctant to add Groovy to production code until their developers have a certain minimum comfort level with the language. As it happens, there are two major areas where Groovy can strongly impact and simplify Java projects without being integrated directly. The first of those is one of the major pain points in enterprise development: the build process. The other is testing, which is valued more highly the better the developer.

By covering these two techniques early in the book I can then use, for example, Gradle builds and Spock tests when I attack the use cases Java developers typically encounter, like web services, database manipulation, or working with the Spring framework.

www.it-ebooks.info

Part 2

Groovy tools

Welcome to part 2: “Groovy tools.” In these two chapters, I address two of the major ways Groovy is often introduced into an organization: namely, build processes and testing.

Chapter 5 on build processes reviews the dominant build tools in the Java world, Ant and Maven, and shows how to add Groovy dependencies to each. It also covers the Ant tasks that work with Groovy and the major Groovy plugins for Maven. Finally, it provides an introduction to Gradle, one of the most important projects in the Groovy world, and includes examples covering several interesting build tasks.

Chapter 6 on testing starts with JUnit tests in both Java and Groovy and then looks at the JUnit subclass GroovyTestCase and its descendants and what additional capabilities they bring. Then it covers the MockFor and StubFor classes in the Groovy library, which are great ways to build mock objects and also provide some insight into Groovy metaprogramming. Finally, the chapter ends with a good overview of the Spock testing framework, which includes mocking capabilities of its own.

www.it-ebooks.info

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]