mdoery ~ software development

adventures in coding

working with json in android apps

| Comments

Summary: Extracting data from a JSON formatted file is pretty simple in Android.

I’m planning to store data in the JSON format for the app that I’m currently building. So here’s a quick post which demonstrates the procedure for reading JSON into data which can be used in your app.

  1. Create an Android application project called MainJson in Eclipse.
  2. Set the Minimum Required SDK property to API 8: Android 2.2 (Froyo), and the Target SDK to API 17: Android 4.2 (Jelly Bean). I tested this tutorial with these parameters.
  3. Set the package name to be com.mdoery.tut.json.
  4. Start the project with a blank Activity.
  5. Create a sub-directory called json under the assets folder; we’ll store our JSON file here.

Now that the project is ready, create a file with JSON-formatted data as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{"sculptors": [
    {"sculptor": {
        "firstname": "Isamu",
        "lastname": "Noguchi",
        "sculptures": [
            {"sculpture": {"name": "Red Cube", "date": "1968"}},
            {"sculpture": {"name": "Black Sun", "date": "1969"}},
            {"sculpture": {"name": "Sky Gate", "date": "1977"}}
        ]
    }},
    {"sculptor": {
      "firstname": "David",
      "lastname": "Smith",
      "sculptures": [
        {"sculpture": {"name": "Medals for Dishonor", "date": "1937-40"}},
        {"sculpture": {"name": "Agricola I", "date": "1952"}},
        {"sculpture": {"name": "CUBI VI", "date": "1963"}}
      ]
    }},
    {"sculptor": {
      "firstname": "Rachel",
      "lastname": "Whiteread",
      "sculptures": [ {"sculpture": {"name": "House", "date": "1993"}} ]
    }}
  ]
}

Call the file sculptors.json, and add it to the assets/json folder.

Finally, open the MainActivity java class, which was created by default, and edit it to contain the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.mdoery.tut.json;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;

public class MainActivity extends Activity {

  private static String sep = System.getProperty("line.separator");
  private static String br = "<br>";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tv = (TextView)this.findViewById(R.id.textView1);
    try {
      // Read contents of file sculptors.json 
      String json = getText("json/sculptors.json",
        getApplicationContext()) + sep;
      // Display it in TextView
      displaySculptorNames(tv, json);
    } catch (Exception e) {
      // If there is an exception, show it in the TextView
      tv.setText("Exception: " + sep + e + sep);
    }
  }

  private String getText(String filename, Context ctx)
    throws IOException {
    InputStream is = ctx.getAssets().open(filename);
    // We guarantee that the available method returns 
    // the total size of the asset not more than 2G.
    int size = is.available();
    // Read the entire asset into a local byte buffer.
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();
    String text = new String(buffer);
    return text;
  }

  /**
   * Extracts information from JSON text, and displays it in TextView 
   * @param tv TextView
   * @param json String of json from file sculptors.json
   * @throws JSONException
   */
  private void displaySculptorNames(TextView tv, String json)
    throws JSONException {
    String text = "";
    JSONTokener tokener = new JSONTokener(json);
    JSONObject object = (JSONObject) tokener.nextValue();
    JSONArray sculptors = object.getJSONArray("sculptors");
    for (int ii = 0; ii < sculptors.length(); ii++) {
      text += (ii + 1) + ") ";
      JSONObject obj = sculptors.getJSONObject(ii);
      JSONObject sculptor = obj.getJSONObject("sculptor");
      String firstname = sculptor.getString("firstname");
      String lastname = sculptor.getString("lastname");
      JSONObject sculpture = sculptor.getJSONArray("sculptures")
        .getJSONObject(0).getJSONObject("sculpture");
      String name = "<i>" + sculpture.get("name") + "</i>";
      text += firstname + " " + lastname + " sculpted " + name;
      String date = sculpture.getString("date");
      try {
        Integer.parseInt(date);
        text += " in " + date;
      } catch (NumberFormatException e) { // catch date range
        text += " during " + date;
      }
      text += br;
    }
    Spanned span = Html.fromHtml(text);
    tv.setText(span);
  }
}

If you run this in the emulator, you should see a screen with text created from the information extracted from the JSON file, like this:

As an aside, notice that some of the text is formatted in italics. That was done using Html.fromHtml in the code. I found out how to do that at Stealthcopter.com.

BTW, here’s a handy tip if you want to try this project with your own JSON: validate JSON before trying to read it in your app. It may save you some trouble! I used jsonlint to do so.

Comments