The first thing we will do is setup our JSON string, which we'll end up parsing.
String jsonStr = '{"menu": {' +
'"id": "file",' +
'"value": "File",' +
'"popup": {' +
'"menuitem": [' +
'{"value": "New", "onclick": "CreateNewDoc()"},' +
'{"value": "Open", "onclick": "OpenDoc()"},' +
'{"value": "Close", "onclick": "CloseDoc()"}' +
']' +
'}' +
'}}';
import org.json.JSONObject;
JSONObject jsonObj = new JSONObject(jsonStr);
With that instantiated, we can do the following to retreive different pieces of data from the JSON string - you will also need the following import for JSONArray:import org.json.JSONArray; and import android.util.Log; for Log.
// grabbing the menu object
JSONObject menu = jsonObj.getJSONObject("menu");
// these 2 are strings
String id = menu.getString("id");
String value = menu.getString("value");
// the popop is another JSON object
JSONObject popup = menu.getJSONObject("popup");
// using JSONArray to grab the menuitems from under popop
JSONArray menuitemArr = popupObject.getJSONArray("menuitem");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
Log.v(menuitemArr.getJSONObject(i).getString("value").toString());
Log.v(menuitemArr.getJSONObject(i).getString("onclick").toString());
}
No comments:
Post a Comment