Java Reference
In-Depth Information
In Listing 11-5, we observe that the questions are in an array named items, starting with the left square bracket
([). We can obtain this JSON array using the following statement:
JsonArray jsonArray = jsonObject.getJsonArray("items");
Next, we need to iterate over all these elements. For every item we encounter, we want to create a Question
instance.
Iterating over the array elements can be done using
jsonArray.iterator().forEachRemaining((JsonValue e) -> {
...
}
To create a Question instance, we need to obtain the name of the author, the title, and the creation date of the
question. The Java JSON API provides a standard way for doing this:
JsonObject obj = (JsonObject) e;
JsonString name = obj.getJsonObject("owner").getJsonString("display_name");
JsonString quest = obj.getJsonString("title");
JsonNumber jsonNumber = obj.getJsonNumber("creation_date");
Finally, we need to create a Question instance based on this information, and add it to the ObservableList
instance we will return:
Question q = new Question(name.getString(), quest.getString(), jsonNumber.longValue() * 1000);
answer.add(q);
This example shows that it is very easy to retrieve and read JSON data obtained from a REST endpoint, and
convert the result into a ListView . In the next section, we demonstrate a similar process for XML responses.
XML Response Format
The XML format is widely used in the Java platform. As a consequence, standardization of XML-based operations in
Java happened years ago. There are a number of XML tools built into the Java Platform, Standard Edition, and we can
use these APIs and tools in JavaFX without any external dependency. In this section, we first use a DOM processor
for parsing the XML response that we artificially built. Next, we use the JAXB standard to automatically obtain Java
Objects.
Changing our application from JSON input to XML input requires only the getObservableList method to be
changed. The new implementation is shown in Listing 11-8.
Listing 11-8. Obtaining Questions from the XML-Based Response
ObservableList<Question> getObservableList() throws IOException, ParserConfigurationException,
SAXException {
ObservableList<Question> answer = FXCollections.observableArrayList();
InputStream inputStream = this.getClass().getResourceAsStream("/stackoverflow.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputStream);
NodeList questionNodes = doc.getElementsByTagName("item");
int count = questionNodes.getLength();
 
Search WWH ::




Custom Search