Android JSON Parsing


JSONĀ  is one of the mostly used data transferring technique that used by developers. there are plenty of JSON parser’s that can be used to convert any given object to a JSON string by mapping relevant key value pairs.

JSONObject object = new JSONObject(jsonString);

in the most abstract way we can pass an json sting to this default android json parser and retrieve the data in the string by passing correct keys to it.

{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}

As an example if we parse the above mentioned JSON String the java based code is as follows,if i take the above mentioned code into an Variable called jsonString and i will pass it to the first json Object’s parameter marking it as an valid json string

JSONObject object = new JSONObject(jsonString);
JSONObject menuObject = object.getJSONObject("menu");
JSONObject popUpObject = menuObject.getJSONObject("popup");
JSONArray menuItemsArray = popUpObject.getJSONArray("menuitem");

Above mentioned code will parse the JSON String and in the final statement it will parse the JSON Array and by using the index we can access the respective JSONObject inside the array Example : menuItemsArray[0] will return the first JSONObject inside the array. This is the most common usage of JSON Parsing other than this we can use frameworks like FlexJson

In the next post we will be talking about how to use flexjson and step by step configuration of flexjson …

Leave a comment