Always On, Always Connected Week 6 - Network Services

Accessing External Data via JSON

JSON

JSON stands for JavaScript Object Notation. It has become a standard way to provide machine readable data to and from web services. Despite the fact that JavaScript is part of it's title, it is generally useful in all programming languages.

As stated on the json.org site: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

A simple JSON object
{
	fist_name: "Shawn",
	last_name: "Van Every
}		
		
An array of JSON objects
[
{
	fist_name: "Shawn",
	last_name: "Van Every"
},
{
	fist_name: "Joe",
	last_name: "Frank"
}		
]		
values can be string, number, null or boolean (true/false)

Here is a JSON feed from Twitter of a user's tweets: vanevery's tweets in JSON

gson

You can parse JSON with Android using classes in the org.json package that comes with Android or you can use the Google gson library which is a lot easier.

The gson library will automatically parse the JSON data in to Java classes provided that you create the class that the data represents.

For instance to parse the above example JSON object, I would need a Java class that looked like this:
		
class Name
{
	public String first_name;
	public String last_name;
}
		
Here is a full example of pulling tweets from Twitter: JSON with gson Example


Screencast covering it MP4 or WebM

Here is an example pulling JSON data from Flickr and displaying the images. This version doesn't use the gson library so it is a bit more verbose: FlickrJSONwLocation.zip