Hello My simple Json is and i have error org.json.JSONException: Index 2 out of range can you help me to solve this problem ? :
[
{
"cat_id": 593,
"title": "آلرژی و ایمونولوژی",
"sub_cat": [
{
"cat_id": 594,
"cat_title": "متخصص",
"cat_parent_fk": 593
},
{
"cat_id": 595,
"cat_title": "فوق تخصص",
"cat_parent_fk": 593
}
]
and get this json with this code but i have some error and just show two item of my json >15 item :
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Cats cats = new Cats();
JSONObject jsonObject = (JSONObject) response.get(i);
String cat_id = jsonObject.getString("cat_id");
String title = jsonObject.getString("title");
String image_add = jsonObject.getString("image_add");
String image = jsonObject.getString("image");
JSONArray jsonArray = jsonObject.getJSONArray("sub_cat");
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(i);
int sub_cat_id = object.getInt("cat_id");
String sub_cat_title = object.getString("cat_title");
int sub_parent_fk = object.getInt("cat_parent_fk");
Log.i("log", "onResponse: "+ sub_cat_id + sub_cat_title + sub_parent_fk);
}
cats.setCat_id(cat_id);
cats.setTitle(title);
cats.setImage(image);
cats.setImage_add(image_add);
list.add(cats);
catsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Instead of i you should use j here as
JSONObject object = jsonArray.getJSONObject(j);
// ^^
Let's assume that your response has 3 json objects and every sub_cat has 2 objects so during the parsing of 3rd object of response (when i is 2) but sublist has 2 objects (index 0,1) so know (as mentioned above) this will try to fetch 3rd object from an array(sub_cat) of 2 objects, hence the issue so use
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
// j represents the size of sub_cat. ^^
...
}
I need to parse my JSON to my Android application, I’m getting an error:
org.json.array cannot be converted to jsonobject
What I want to do is to take the json from my server and parse it into the textviews that i had made I’m using AsyncHttpClient, here is my code.
AsyncHttpClient client1 = new AsyncHttpClient();
client1.get("http://mahmoudfa-001-site1.atempurl.com/appetizers.json",new
TextHttpResponseHandler() {
#Override
public void onFailure ( int statusCode, Header[] headers, String responseString, Throwable throwable){
}
#Override
public void onSuccess ( int statusCode, Header[] headers, String responseString){
Log.i("a1", responseString);
//testing if the server responding.
Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_LONG).show();
try {
JSONObject job = new JSONObject(responseString);
JSONArray arr = new JSONArray(build);
//String arrlen = Integer.toString(arr.length());
JSONObject na = arr.getJSONObject(0);
JSONArray ingna = na.getJSONArray("unavailable");
String[] ingr = new String[ingna.length()];
for (int k = 0; k < ingna.length(); k++) {
JSONObject abc = ingna.getJSONObject(k);
ingr[k] = abc.getString("ingredient");
}
for (int i = 1; i < arr.length(); i++) {
JSONObject food = null;
food = arr.getJSONObject(i);
String name = food.getString("name");
String description = food.getString("description");
String rating = food.getString("rating");
String price = food.getString("price");
String cooktime = food.getString("cooktime");
JSONArray ingredients = food.getJSONArray("ingredients");
String[] ing = new String[ingredients.length()];
for (int k = 0; k < ingredients.length(); k++) {
JSONObject ingd = ingredients.getJSONObject(k);
ing[k] = ingd.getString("ingredient");
}
for (int l = 0; l < ing.length; l++) {
for (int m = 0; m < ingr.length; m++) {
if (ing[l].matches(ingr[m])) ;
}
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONObject job = new JSONObject(responseString);
JSONArray arr = new JSONArray(build);
//String arrlen = Integer.toString(arr.length());
JSONObject na = arr.getJSONObject(0);
JSONArray ingna = na.getJSONArray("unavailable");
String[] ingr = new String[ingna.length()];
for (int k = 0; k < ingna.length(); k++) {
JSONObject abc = ingna.getJSONObject(k);
ingr[k] = abc.getString("ingredient");
}
for (int i = 1; i < arr.length(); i++) {
JSONObject food = null;
food = arr.getJSONObject(i);
String name1 = food.getString("name");
if (name.equals(name1)) {
imageUrl[0] = imageUrl[0] + i;
nametext.setText("Name : " + name);
String description = food.getString("description");
detailstext.setText("Description : " + description);
String rating = food.getString("rating");
String price = food.getString("price");
price1 = Integer.parseInt(price);
pricetext.setText("Price : Rs. " + price);
ratingtext.setText("Rating : " + rating + " stars");
String cooktime = food.getString("cooktime");
cooktimetext.setText("Cooktime : " + cooktime);
JSONArray ingredients = food.getJSONArray("ingredients");
String[] ing = new String[ingredients.length()];
for (int k = 0; k < ingredients.length(); k++) {
JSONObject ingd = ingredients.getJSONObject(k);
ing[k] = ingd.getString("ingredient");
}
String ingre = "Ingredients:";
for (int k = 0; k < ing.length; k++) {
if (k < (ing.length - 1))
ingre = ingre + " " + ing[k] + ",";
else
ingre = ingre + " " + ing[k];
}
ingredientstext.setText(ingre);
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Please I need help..
this is the JSON I am getting from my server:
[
{
"unavailable" :
[
{
"ingredient" : "Prawn"
},
{
"ingredient" : "Paneerygf"
},
{
"ingredient" : "Fish1"
}
]
},
{
"name" : "Paneer Chilly",
"description" : "Fried paneer pieces in chilly gravy",
"rating" : "4",
"price" : "100",
"cooktime" : "20 mins",
"ingredients" : [
{"ingredient":"Paneer"}
]
},
{
"name" : "Prawn Stuff Papad",
"description" : "Papad stuffed with prawns and spices",
"rating" : "3",
"price" : "150",
"cooktime" : "25 mins",
"ingredients" : [
{"ingredient":"Prawn"}
]
},
{
"name" : "Fish Chilly",
"description" : "Fired fish fillets with chilly gravy",
"rating" : "3",
"price" : "175",
"cooktime" : "25 mins",
"ingredients" : [
{"ingredient":"Fish"}
]
}
]
The response returned from http://mahmoudfa-001-site1.atempurl.com/appetizers.json is a JSONArray, not a JSONObject. You should parse it by JSONArray jsonArray = new JSONArray(responseString).
i'm trying to parse this below json format such as:
[
[
{
"mobileNumber":"<Censored>","contactUserId":"17",
"userEwallets":
[
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"}
]
}
]
,
[
{
"mobileNumber":"<Censored>","contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]
]
for parsing second json array of that as
[
{
"mobileNumber":"<Censored>",
"contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]
i get this error:
Index 1 out of range [0..1)
from below code my code can only parse the first array of that, for second array i get exception when i try to get mobileNumber of second json array object
for (int i = 0; i < response.length(); i++) {
try {
JSONArray jsonArray = response.getJSONArray(i);
final String mobileNumber = jsonArray.getJSONObject(i).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(i).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(i).getString("userEwallets");
Log.e("MobileNumber ", mobileNumber);
JSONArray ewallets = new JSONArray(userEwallets);
for (int j = 0; j < ewallets.length(); j++) {
JSONObject ewalletObject = ewallets.getJSONObject(j);
final String accountNumber = ewalletObject.getString("accountNumber");
Log.e("accountNumber ", accountNumber);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Try this one...
JSONArray response;
try {
response = new JSONArray(res);
for (int i = 0; i < response.length(); i++) {
JSONArray insideJSONArray = response.getJSONArray(i);
JSONObject jsonObject = insideJSONArray.getJSONObject(0);
String mobileNumber = jsonObject.getString("mobileNumber");
Log.e("TAG", "mobileNumber: " + mobileNumber);
String contactUserId = jsonObject.getString("contactUserId");
Log.e("TAG", "mobileNumber: " + contactUserId);
JSONArray userEwallets = jsonObject.getJSONArray("userEwallets");
for (int j = 0; j < userEwallets.length(); j++) {
JSONObject ewalletObject = userEwallets.getJSONObject(j);
final String accountNumber = ewalletObject.getString("accountNumber");
Log.e("accountNumber ", accountNumber);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Change:
final String mobileNumber = jsonArray.getJSONObject(i).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(i).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(i).getString("userEwallets");
to
final String mobileNumber = jsonArray.getJSONObject(0).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(0).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(0).getString("userEwallets");
how I can access data from a JSONArray? It is this and contains this information:
"deadlines": [
{
"start": 1439539200,
"end": 1439542800
},
{
"start": 1440144000,
"end": 1440147600
},
{
"start": 0,
"end": 0
}
]
I need to have in a String tag each item "start". Thanks
EDIT
My code is this:
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
for (int j=0; j < array.length(); j++)
{
try
{
JSONObject obj = array.getJSONObject(j);
String start = obj.getString("start");
String end = obj.getString("end");
Log.e("", "start = " + start);
}
catch (JSONException e)
{
Log.e("", "error = " + e.getMessage());
}
}
I get this error:
"error = No value for start"
Do this
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
JSONArray jArray = array.getJSONObject(0).getJSONArray("deadlines");
for (int i = 0; i < jArray.length(); i++) // assuming your array is jArray
{
try
{
JSONObject obj = jArray.getJSONObject(i);
String start= obj.getString("start"); // store in an ArrayList
String end = obj.getString("end"); //// store in an ArrayList
}
catch (JSONException e)
{
// Error
}
}
JSONArray mJsonArray=new JSONArray("Deadlines");
for(int i=0;i<mJsonArray.length();i++){
JSONObject mJsonObject=new JSONObject(mJsonArray.get(i).toString));
String start = mJsonObject.optString("start","");
String end = mJsonObject.optString("end","");
}
Try this:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray("deadlines");
for(int i=0;i<arr.length;i++){
JSONObject obj = arr.getJSONObject(i);
sb.append(obj.get("start").toString());
sb.append(",");
}
String strStartTag = sb;
JSONArray ja = new JSONArray(yourjsondata));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo_feed = new JSONObject(ja.get(i).toString());
String start = jo_feed.getString("start");
}
JSON is only displaying the last object '100 g' of "serving_description" in the JSON Formatted Data, See below. instead of all of the "serving_description" objects.
The Array is serving
If you look at the JSON Formatted Data below you will see that there are multiple "serving_description" 's.
I am trying to get the "serving_description" of all of the the available options to display instead of the last object in which it is displaying. How do I display all of the "serving_descriptions"?
I believe the error lies in, but I can be wrong, that is why I am asking :
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
Class, AsyncTask
#Override
public void onClick(View v) {
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... arg0) {
search = (EditText) findViewById(R.id.editText1);
String SEARCH = search.getText().toString();
JSONObject food = getFood(SEARCH);
Log.v("FATSEC", "TEST");
String ret = "";
try {
JSONArray foodName = food.getJSONObject("food")
.getJSONObject("servings")
.getJSONArray("serving");
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object
.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
} catch (JSONException e) {
e.printStackTrace();
}
return ret;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// ans.setText("# of Servings: " + result);
ans.setText("Servings: " + result);
}
}.execute();
}
});
Formatted JSON DATA
{
"servings":{
"serving":[
{
"vitamin_a":"0",
"calcium":"2",
"serving_description":"1 cup cooked",
"vitamin_c":"0",
"carbohydrate":"44.08",
"metric_serving_unit":"g",
"fat":"0.44",
"sodium":"577",
"polyunsaturated_fat":"0.119",
"fiber":"0.6",
"cholesterol":"0",
"iron":"10",
"serving_id":"16834",
"protein":"4.20",
"monounsaturated_fat":"0.138",
"potassium":"55",
"number_of_units":"1.000",
"calories":"204",
"measurement_description":"cup, cooked",
"saturated_fat":"0.120",
"metric_serving_amount":"158.000",
"sugar":"0.08",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=16834&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"6",
"serving_description":"1 cup, dry, yields",
"vitamin_c":"0",
"carbohydrate":"159.03",
"metric_serving_unit":"g",
"fat":"1.60",
"sodium":"2080",
"polyunsaturated_fat":"0.429",
"fiber":"2.3",
"cholesterol":"0",
"iron":"38",
"serving_id":"15284",
"protein":"15.16",
"monounsaturated_fat":"0.497",
"potassium":"200",
"number_of_units":"1.000",
"calories":"735",
"measurement_description":"cup, dry, yields",
"saturated_fat":"0.432",
"metric_serving_amount":"570.000",
"sugar":"0.29",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=15284&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 oz, dry, yields",
"vitamin_c":"0",
"carbohydrate":"24.27",
"metric_serving_unit":"g",
"fat":"0.24",
"sodium":"318",
"polyunsaturated_fat":"0.065",
"fiber":"0.3",
"cholesterol":"0",
"iron":"6",
"serving_id":"18252",
"protein":"2.31",
"monounsaturated_fat":"0.076",
"potassium":"30",
"number_of_units":"1.000",
"calories":"112",
"measurement_description":"oz, dry, yields",
"saturated_fat":"0.066",
"metric_serving_amount":"87.000",
"sugar":"0.04",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=18252&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 serving (105 g)",
"vitamin_c":"0",
"carbohydrate":"29.30",
"metric_serving_unit":"g",
"fat":"0.29",
"sodium":"383",
"polyunsaturated_fat":"0.079",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"17592",
"protein":"2.79",
"monounsaturated_fat":"0.092",
"potassium":"37",
"number_of_units":"1.000",
"calories":"135",
"measurement_description":"serving (105g)",
"saturated_fat":"0.080",
"metric_serving_amount":"105.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=17592&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"100 g",
"vitamin_c":"0",
"carbohydrate":"27.90",
"metric_serving_unit":"g",
"fat":"0.28",
"sodium":"365",
"polyunsaturated_fat":"0.075",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"53181",
"protein":"2.66",
"monounsaturated_fat":"0.087",
"potassium":"35",
"number_of_units":"100.000",
"calories":"129",
"measurement_description":"g",
"saturated_fat":"0.076",
"metric_serving_amount":"100.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=53181&portionamount=100.000"
}
]
},
"food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular",
"food_type":"Generic",
"food_name":"White Rice",
"food_id":"4501"
}
Use + to append all serving_description value in ret as:
ret += shit + "\n\n";
Each iteration of the loop overrides the value of ret so that you are never able to accumulate them. For this reason, when you return it has the last value you stored there and none of the previous values that were wiped out. Consider using a StringBuilder.
StringBuilder builder = new StringBuilder();
...
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
builder.append(shit).append("\n");
}
...
return builder.toString();