Recipe 6.5 Consuming JSON Web Services
Apart from XML web services, another type of web service that is gaining popularity is JSON (JavaScript Object Notation). JSON is a lightweight data interchange format that is designed to be easy to be processed by both humans and machines. Instead of using tags (such as <title> and </title>) to represent the meaning of data in an XML document, JSON uses braces (“{”, “}”), colons (“:”), and brackets (“[”, “]”) to organize data in name/value pairs and arrays.
This recipe shows you how to consume JSON web services in your Android application.
Solution
For this recipe, you will consume two JSON web services:
- GeoNames JSON web service — Offers a service that returns the weather for a given location. The result is returned as a JSON string.
- GeoNames Postal Code Search — Offers a service that returns a list of city names matching a given postal code.
To connect to the web services and obtain the returning JSON string, simply connect to the server using HTTP GET or POST (for simplicity, this example uses HTTP GET; see the Recipe 6.1), and then obtain the returning string (which is in JSON format). The following readJSONFeed() method does just that:
public String readJSONFeed(String URL) { StringBuilder stringBuilder = new StringBuilder(); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access