Recipe 6.5 Consuming JSON Web Services

Android Versions
Level 1 and above
Permissions
android.permission.INTERNET
Source Code to Download at Wrox.com
JSON.zip

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 = ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.