Java Reference
In-Depth Information
Before we dive into the code, we show the result of the modified application in Figure 11-5 .
Figure 11-5. The result of the StackOverflowApplication retrieving JSON data
The code in Listing 11-7 can be divided into four parts:
1.
Call the REST endpoint.
2.
Obtain the raw JSON data.
3.
Convert each item into a question.
4. Add the Questions to the result.
Calling the REST endpoint is very straightforward:
String url = " http://api.stackexchange.com/2.2/search?tagged=javafx&site=stackoverflow ";
URL host = new URL(url);
JsonReader jr = Json.createReader(new GZIPInputStream(host.openConnection().getInputStream()));
First, we create a URL Object that refers to the desired location. Next, we open the connection to the location.
Because StackExchange is sending its data as zipped data, we open a GZIPInputStream using the InputStream obtained
from the connection. We pass this GZIPInputStream as the InputStream argument in the Json.createReader() method.
We now have a JSON reader that consumes the data we want to have. Extracting Java Objects from this JSON
reader manually requires specific code for a specific case.
We could also have used a JsOn parser instead of a JsOn reader. it is not our intention to deliver an exhaustive
JsOn parsing guide. We only try to show how JsOn data can be converted into Java Objects for our specific use case.
You can easily find a number of tutorials on JsOn on the internet.
Note
 
 
Search WWH ::




Custom Search