I'm using the below code to take the values of price. I can get the value for price. However, when it comes to crust it runs to the exception.
@Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> crust = new ArrayList<String>();
List<String> price = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
Log.i("Price ", object.getString("Price"));
price.add(object.getString("Price"));
Log.i("Crust ", object.getString("Crust"));
crust.add(object.getString("Crust"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this is the json response
{
"Category":"1PI",
"Price":0.0000,
"SubCategoryID":1,
"SubMenu":true,
"SubMenuEntity":[
{
"Crust":"Sausage",
Crust is positioned in, array inside an array, how can i access crust in my above coding.
any help will be appreciated.
SubMenuEntity item has an array of objects. You need to get the array and loop though it. For each object, get the value of Crust.
try {
List<String> crust = new ArrayList<String>();
List<String> price = new ArrayList<String>();
JSONArray responseJson = null;
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
Log.i("Price ", object.getString("Price"));
price.add(object.getString("Price"));
JSONArray subMenuArray = object.getJSONArray("SubMenuEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray.getJSONObject(j);
Log.i("Crust ", subMenuObject.getString("Crust"));
crust.add(subMenuObject.getString("Crust"));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}