Java Reference
In-Depth Information
Listing 9.10. Parsing a Person instance from a string
public Person readFrom(Class<Person> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream)
throws IOException, WebApplicationException {
def json = new JsonSlurper().parseText(entityStream.text)
Person p = new Person(id:json.id, first:json.first, last:json.last)
if (json.links) {
p.prev = Link.valueOf(json.links.prev)
p.self = Link.valueOf(json.links.self)
p.next = Link.valueOf(json.links.next)
}
return p
}
The readFrom method uses the JsonSlurper 's parseText method to convert the
input text data into a JSON object and then instantiates a Person based on the resulting
properties. If links exist in the body, they're converted using the valueOf method.
To use the MessageBodyWriter , I need to add an @Provider annotation to the im-
plementation class andmakesureit'sloadedintheapplication. Thelatter isdonebyadding
the provider to the MyApplication class:
public class MyApplication extends ResourceConfig {
public MyApplication() {
super(PersonResource.class, PersonProvider.class,
JacksonFeature.class);
}
}
In this case both the PersonProvider and the JacksonFeature are used. The
Person provider converts individual Person instances to JSON, and the Jack-
sonFeature handles collections. A test of the resulting structure looks like this:
def 'transitional links for kirk are correct'() {
when:
def response = client.get(path: 'people/3')
then:
'James Kirk' == "$response.data.first $response.data.last"
Link.valueOf(response.data.links.prev).uri ==
'http://localhost:1234/people/2'.toURI()
Search WWH ::




Custom Search