Sunday, February 17, 2013

JSON in Android

In this post I will show you how to get JSON data from a HTTP server and parse it in android.
The JSON data that we will parse in this tutorial is the following:

{
  "status" : "ok",
  "score" : 101,
  "friends" : [{"id" : 321, "score" : 100}, {"id" : 320, "score" : 105}]
}

We will assume that you can access this data from the URL: http://server.com/json

The first step is to get the data in you android application. Since we will download it from a server, you will first need to specify the internet permission in you Android Manifest file:

<uses-permission android:name="android.permission.INTERNET" />

Now that we set this permission, we can download the data. Since we can't use the main thread for networking, we will create a new thread to download our data and parse it. Add the following code in your onCreate method, in your Activity class.

new Thread() {
  public void run() {
    helloJson();
  }
}.start();

Next, we will create the helloJson method, containing the following code:

public void helloJson() {
    StringBuilder builder = new StringBuilder();
    
    try {
      HttpClient client = new DefaultHttpClient();
      HttpGet httpGet = new HttpGet("http://server.com/json");
  
      HttpResponse response = client.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        InputStreamReader reader = new InputStreamReader(content)
        BufferedReader reader = new BufferedReader(reader);
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
        JSONObject jobj = new JSONObject(builder.toString());
        builder = new StringBuilder(jobj.get("status").toString());
        JSONArray jar = jobj.optJSONArray("friends");
        builder.append(jar.length());
      }
    }
    catch(Exception e) {
      e.printStackTrace();
      builder.append(e);
    }
    
    final String str = builder.toString();
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();
      }
    });
  }

This will display a message using Toast, containing the status string and the length of the friends array.

That's it! :)

No comments:

Post a Comment