Parsing JSON

First of all, we will start with JSON parsing. Most of that will be handled by the Gson library. However, we still need to correctly create a tree class that will be used to contain it.

Yahoo API returns a structure that should resemble something like this:

{
"query": {
"count": 4,
"created": "2000-00-00T00:00:45Z",
"lang": "en-US",
"results": {
"quote": [
{
"symbol": "YHOO",
"AverageDailyVolume": "10089100",
"Change": "+0.86",
"DaysLow": "41.00",
"DaysHigh": "42.00",
"YearLow": "26.15",
"YearHigh": "44.00",
"MarketCapitalization": "40.00B",
"LastTradePriceOnly": "42.00",
"DaysRange": "41.54 - 42.37",
"Name": "Yahoo! Inc.",
"Symbol": "YHOO",
"Volume": "4645383",
"StockExchange": "NMS"
},
...
]
}
}
}

Different levels of nesting will require multiple classes. For this purpose, we will create and put them into the packt.reactivestocks.yahoo.json package.

Let's start with the root class of YahooStockResult, which is a very simple wrapper:

public class YahooStockResult {
private YahooStockQuery query;

public YahooStockQuery getQuery() {
return query;
}
}

It's a very similar case with the YahooStockQuery class:

public class YahooStockQuery {
private int count;
private Date created;
private YahooStockResults results;
...
}

Here, we have skipped getters for the sake of simplicity.

The YahooStockResults class can look as follows:

public class YahooStockResults {
private List<YahooStockQuote> quote;
...
}

Finally, YahooStockQuote will have a bit more in it than other classes:

public class YahooStockQuote {
private String symbol;

@SerializedName
("Name")
private String name;

@SerializedName
("LastTradePriceOnly")
private BigDecimal lastTradePriceOnly;

@SerializedName
("DaysLow")
private BigDecimal daysLow;

@SerializedName
("DaysHigh")
private BigDecimal daysHigh;

@SerializedName
("Volume")
private String volume;
...
}

In this case, we have used the @SerializedName annotation to specify the names of the fields in JSON instead of relying on them to be caught by the name of the field. We did this so that we can keep the lowercase field names in the Java code to adhere to Java coding style conventions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.71.106