JSON Parsing in android
Let’s look at how to parse JSON objects in android
1> First we’ll need an example :
Lets look at a standard example from the json site http://json.org/example.html
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
you could either save this in a file or save it in a string…..like I’ve done
2> Android already contains the required JSON libraries
Lets create a JSON Object;
private JSONObject jObject;
and lets our example be a String ,
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
now we have to convert jString to the jObject ,
jObject = new JSONObject(jString);
Now we have to start extracting the content from jObject ,
Lets extract the menu object by creating a new menu object,
JSONObject menuObject = jObject.getJSONObject("menu");
Now lets extract its atrtibutes ,
String attributeId = menuObject.getString("id");
String attributeValue = menuObject.getString("value");
JSONObject popupObject = menuObject.getJSONObject("popup");
since “popup” is not plainly a String lets extract it to an object ,
3> Now popup contains an array of “menuitem”
So, we’ll have to extract it to a JSONArray,
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
Since it contains 3 items lets put it in a for loop.
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
Basically thats it , u should see the output in the DDMS
4> The full code is as below,
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonParser extends Activity {
private JSONObject jObject;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(jString);
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);
String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
}
}
Great!
very good example
@Michel
thanks Michel
Thanks this tutorial helped me a lot. Great share.
Thanks , this tutorial helped me a lot.
Hello,
I have this JSON String:
testing = {“error”:”empty”}
It’s on a correct format right?
When I try to put it on an JSON Array
CODE: SELECT ALL
info = new JSONArray(testing);
I always get this JSON Exception:
CODE: SELECT ALL
org.json.JSONException: A JSONArray text must start with ‘[' at character 1 of {"error":"empty"}
I mean.. the String is already in the JSON String format so I really don't understand what's going on. I tried to append the ''[]” it doesn’t give me the exception anymore, but I’m also not able to retrieve the values I want in this case info.getString(0) which would give me the ”error”.
Does anyone have any ideia what I’m doing wrong? I’ve been through JSON parsing tutorials, and I’m doing like they say…
I wrote up a very extensive tutorial on using JSON in Android (that also deals with best practices for downloading files using Android) that I think would be very, very helpful to anyone using this page. You can find it here:
http://blog.andrewpearson.org/2010/07/android-why-to-use-json-and-how-to-use.html
@Pedro Teixeira
Pedro, hopefully you figured this out, but the testing variable you are passing into JSONArray is not an array but a hash (or associative array). If you were to use ['error', 'empty'] then it would parse, but I don’t think that is what you want to do. If I understand your intention correctly, you want to retrieve the “empty” value from this hash by specifying the key “error”. To do this, use this code:
jObject = new JSONObject(testing);
String theError = (String)jObject.getJSONObject(“error”);
Now, theError should have the correct value of “empty”.
Doh, actually the second line should be:
String theError = jObject.getString(“error”);
I am not sure it really makes sense to use the default JSON parser (one from json.org) — it is very clumsy, inefficient and lots of code to write. Rather, packages like Gson and Jackson make JSON handling much much more convenient. So while tutorials are good, I really wish they actually tried to show best practices and not just arbitrary ways.