Introduction
This tip explains how do parse JSON data in any Android application using JSONObject class.
Using the Code
So, here is an example of the data that I'm trying to parse. It's a dummy list of two chemistry elements with values, inside a JSON file. I have named the file chem_elements.json and it's in my assets folder inside my IDE (using Android Studio). Here is the dummy data:
{
"Hydrogen": {
"symbol" : "H",
"atomic_number" : 1,
"atomic_weight" : 1.00794
},
"Helium": {
"symbol" : "He",
"atomic_number" : 2,
"atomic_weight" : 4.002602
}
}
Here is the Java method that will parse the JSON file and will return a JSON object. Make sure the JSON file is in assets folder inside your Android project, because otherwise you will get a file not found exception.
import org.json.JSONException;
import org.json.JSONObject;
public JSONObject parseJSONData() {
String JSONString = null;
JSONObject JSONObject = null;
try {
InputStream inputStream = getAssets().open("chem_elements.json");
int sizeOfJSONFile = inputStream.available();
byte[] bytes = new byte[sizeOfJSONFile];
inputStream.read(bytes);
inputStream.close();
JSONString = new String(bytes, "UTF-8");
JSONObject = new JSONObject(JSONString);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
catch (JSONException x) {
x.printStackTrace();
return null;
}
return JSONObject;
}
Now, we need to use the JSON object and retrieve the data from the file. As you can see in the raw JSON file, there is a hierarchy involved. There are elements (Hydrogen, Helium) and then each element has values. Here is the example that shows how to retrieve different values.
JSONObject parent = this.parseJSONData();
String element = parent.getString("Hydrogen");
String atomicNumber = parent.getJSONObject("Hydrogen").getString("atomic_number");
This is it, you can now retrieve any data inside the JSON file using the above calls.
Points of Interest
I always wanted to learn about JSON file format, but did not know it was this easy. :)