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.
Create an Android application project called MainJson in Eclipse.
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.
Set the package name to be com.mdoery.tut.json.
Start the project with a blank Activity.
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:
1234567891011121314151617181920212223242526
{"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:
packagecom.mdoery.tut.json;importjava.io.IOException;importjava.io.InputStream;importorg.json.JSONArray;importorg.json.JSONException;importorg.json.JSONObject;importorg.json.JSONTokener;importandroid.os.Bundle;importandroid.app.Activity;importandroid.content.Context;importandroid.text.Html;importandroid.text.Spanned;importandroid.widget.TextView;publicclassMainActivityextendsActivity{privatestaticStringsep=System.getProperty("line.separator");privatestaticStringbr="<br>";@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextViewtv=(TextView)this.findViewById(R.id.textView1);try{// Read contents of file sculptors.json Stringjson=getText("json/sculptors.json",getApplicationContext())+sep;// Display it in TextViewdisplaySculptorNames(tv,json);}catch(Exceptione){// If there is an exception, show it in the TextViewtv.setText("Exception: "+sep+e+sep);}}privateStringgetText(Stringfilename,Contextctx)throwsIOException{InputStreamis=ctx.getAssets().open(filename);// We guarantee that the available method returns // the total size of the asset not more than 2G.intsize=is.available();// Read the entire asset into a local byte buffer.byte[]buffer=newbyte[size];is.read(buffer);is.close();Stringtext=newString(buffer);returntext;}/** * Extracts information from JSON text, and displays it in TextView * @param tv TextView * @param json String of json from file sculptors.json * @throws JSONException */privatevoiddisplaySculptorNames(TextViewtv,Stringjson)throwsJSONException{Stringtext="";JSONTokenertokener=newJSONTokener(json);JSONObjectobject=(JSONObject)tokener.nextValue();JSONArraysculptors=object.getJSONArray("sculptors");for(intii=0;ii<sculptors.length();ii++){text+=(ii+1)+") ";JSONObjectobj=sculptors.getJSONObject(ii);JSONObjectsculptor=obj.getJSONObject("sculptor");Stringfirstname=sculptor.getString("firstname");Stringlastname=sculptor.getString("lastname");JSONObjectsculpture=sculptor.getJSONArray("sculptures").getJSONObject(0).getJSONObject("sculpture");Stringname="<i>"+sculpture.get("name")+"</i>";text+=firstname+" "+lastname+" sculpted "+name;Stringdate=sculpture.getString("date");try{Integer.parseInt(date);text+=" in "+date;}catch(NumberFormatExceptione){// catch date rangetext+=" during "+date;}text+=br;}Spannedspan=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.