Java Reference
In-Depth Information
Validator validator = schema.newValidator()
validator.validate( new StreamSource( new FileReader(file)))
This looks relatively simple, but here's the interesting part: the mechanism used is Java. If
I was to write this code in Java, it would look almost identical. Unlike the XmlSlurper
used for DTD validation, Groovy doesn't add anything special to do schema validation. So
you fall back on the Java approach and write it in Groovy. Because Groovy didn't add any-
thing, these lines could be written in either language, depending on your needs.
Still, Groovy normally does help, as most of the code in this appendix shows.
Whenever the issue of XML comes up these days, someone always asks about JSON sup-
port. I'll address that issue in the next section.
B.9. JSON support
ThetrendintheindustryhasbeenawayfromXMLandtowardJavaScript Object Notation,
known as JSON. If your client is written in JavaScript, JSON is a natural, because JSON
objects are native to the language. Java doesn't include a JSON parser, but several good
libraries are available.
As of Groovy 1.8, Groovy includes a groovy.json package, which includes a JSON
slurper and a JSON builder.
B.9.1. Slurping JSON
The groovy.json package includes a class called JsonSlurper . This class is not
quite as versatile as the XmlSlurper class because it has fewer methods. It contains a
parse method that takes a Reader as an argument, as well as a parseText method
that takes a String .
A JSON object looks like a map inside curly braces. Parsing it results in a map in Groovy:
import groovy.json.JsonSlurper;
def slurper = new JsonSlurper()
Search WWH ::




Custom Search