JSON in Android - Tutorial 1.
Android and JSON
1.1. Android and JSON
JSON is a very condense data exchange format. Android includes the [Link] libraries which allow to work easily with JSON files.
1.2. Twitter
Twitter is a great source for JSON. You can just call a URI and retrieve JSON. Here are some examples: Table 1. Twitter URI's
URI Description
[Link]
Get the timeline of user vogella .
[Link]
Search for the term "android" on Twitter.
[Link]
Returns the user data of user vogella .
Please note that some URI's return a JSONObject object while others return a JSONArray. The following coding uses an URI which returns an JSONArray.
2. Reading JSON
Create a new Android project "[Link]" with the package "[Link]" and the activity "ParseJSON".
Create the following coding for the activity. This will download the twitter feed for the user [Link] write the number of entries and the text messages to the Android log file.
package [Link];
import [Link]; import [Link]; import [Link]; import [Link];
import [Link]; import [Link]; import [Link]; import [Link]; import [Link]; import [Link]; import [Link]; import [Link]; import [Link];
import [Link]; import [Link]; import [Link];
public class ParseJSON extends Activity {
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { [Link](savedInstanceState); setContentView([Link]); String readTwitterFeed = readTwitterFeed(); try { JSONArray jsonArray = new JSONArray(readTwitterFeed); Log.i([Link](), "Number of entries " + [Link]()); for (int i = 0; i < [Link](); i++) { JSONObject jsonObject = [Link](i); Log.i([Link](), [Link]("text")); } } catch (Exception e) { [Link](); } }
public String readTwitterFeed() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet( "[Link] try {
HttpResponse response = [Link](httpGet); StatusLine statusLine = [Link](); int statusCode = [Link](); if (statusCode == 200) { HttpEntity entity = [Link](); InputStream content = [Link](); BufferedReader reader = new BufferedReader( new InputStreamReader(content)); String line; while ((line = [Link]()) != null) { [Link](line); } } else { Log.e([Link](), "Failed to download file"); } } catch (ClientProtocolException e) { [Link](); } catch (IOException e) { [Link](); } return [Link](); } }
To run this example assign the uses-permission to your "[Link]" for "[Link]".
3. Write JSON
Writing JSON is very simple. Just create the JSONObject or JSONArray and use the toString() method.
public void writeJSON() { JSONObject object = new JSONObject(); try { [Link]("name", "Jack Hack"); [Link]("score", new Integer(200)); [Link]("current", new Double(152.32)); [Link]("nickname", "Hacker"); } catch (JSONException e) { [Link](); } [Link](object); }