How to parse JSON in Android Iam using Volley library? - android

{
"destination_addresses" : [ "Bombay, Maharashtra, Inde" ],
"origin_addresses" : [ "New Delhi, New Delhi 110001, Inde" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1 457 km",
"value" : 1457222
},
"duration" : {
"text" : "22 heures 8 minutes",
"value" : 79663
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}

Please use the below code for reference.
JSONObject jsonObject = new JSONObject("jsonResponse");
JSONArray jsonArr= jsonObj.getJSONArray("destination_addresses");
String[] arrDestinations=new String[jsonArr.lLength()];
for(int i=0;i<jsonArr.length();i++)
arrDestinations[i]=jsonArr.get(i);
jsonArr= jsonObj.getJSONArray("origin_addresses");
String[] arrOrigins=new String[jsonArr.lLength()];
for(int i=0;i<jsonArr.length();i++)
arrOrigins[i]=jsonArr.get(i);
JSONArray rows = jsonObj.getJSONArray("rows");
for(int i =0; i < rows.length(); i++)
{
JSONObject rowObj = rows.getJSONObject(i);
JSONArray rowElements = rowObj.getJSONArray("elements");
for(int element = 0; element < rowElements.length(); element++) {
// get the elements and parse
}
}
Hope this helps.

Check your Logcat to see extracted values from JsonObject.
try {
JSONObject jsonObj = new JSONObject(JsonObject.toString());
JSONArray destination_addresses = jsonObj.getJSONArray("destination_addresses");
for (int i = 0; i < destination_addresses.length(); i++) {
Log.e("Values", "destination_addresses = " + destination_addresses.get(i));
}
JSONArray origin_addresses = jsonObj.getJSONArray("origin_addresses");
for (int i = 0; i < origin_addresses.length(); i++) {
Log.e("Values", "origin_addresses = " + origin_addresses.get(i));
}
JSONArray rows = jsonObj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
JSONObject rowObject = rows.getJSONObject(i);
JSONArray rowElements = rowObject.getJSONArray("elements");
for (int j = 0; j < rowElements.length(); j++) {
JSONObject elementObject = rowElements.getJSONObject(j);
JSONObject distanceObject = elementObject.getJSONObject("distance");
String distanceText = distanceObject.getString("text");
String distanceValue = distanceObject.getString("value");
JSONObject durationObject = elementObject.getJSONObject("duration");
String durationText = distanceObject.getString("text");
String durationValue = distanceObject.getString("value");
Log.e("Values", "distanceText = " + distanceText + "\ndistanceValue = " + distanceValue + "\ndurationText = " + durationText + "\ndurationValue = " + durationValue);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

I wrote a library for parsing and generating JSON in Android:
http://github.com/amirdew/JSON

Related

Error org.json.JSONException: Index 2 out of range

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. ^^
...
}

Parsing JSON in Android using AsyncHttpClient

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).

Android get Index 1 out of range on parse json format

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 to get Json key and value with iterator in andorid

How to get this Json key and value from the web. This is my code, but I can't get this from the second iteration. can some one help me to do this.
Json Response :
"attributes": [
{
"main_id": "3",
"Color": [
{
"id": "60",
"text": "46( +$0.00)"
}
]
},
{
"main_id": "21",
"dede": [
{
"id": "73",
"text": "baba( +$0.00)"
}
]
}
]
This is my android code to parse the values :
JSONArray jsonArrayAttributes = jsonObj.getJSONArray("attributes");
for (int i = 0; i < jsonArrayAttributes.length(); i++) {
JSONObject jsonObject1 = jsonArrayAttributes.getJSONObject(i);
Iterator iteratorKey = jsonObject1.keys();
String strAttrId = (String) iteratorKey.next();
String strAttrName = (String) iteratorKey.next();
JSONArray jsonArrayName = jsonObject1.getJSONArray(strAttrName);
for (int j = 0; j < jsonArrayName.length(); j++) {
JSONObject jsonObjName = jsonArrayName.getJSONObject(j);
}
}
You have to change your code little bit like
JSONArray jsonArrayAttributes = jsonObj.getJSONArray("attributes");
for (int i = 0; i < jsonArrayAttributes.length(); i++) {
JSONObject jsonObject1 = jsonArrayAttributes.getJSONObject(i);
Iterator it = jsonObject1.keys();
boolean arrFlag = false;
while (it.hasNext()) {
String key = (String) it.next();
if (!arrFlag) {
String value = jsonObject1.getString(key);
Log.i("Key:Value", "" + key + ":" + value);
arrFlag = true;
} else {
JSONArray value = jsonObject1.getJSONArray(key);
Log.i("Key:Value", "" + key + ":" + value);
arrFlag = false;
}
}
}
It working perfectly.
You will get all keys and value over here.

Parsing JSON in Android; arrayList_ph is null

Please help me to parse the following JSON data given below:
{
posts: [
{
count: 1,
user_id: "1",
name: "Dave Greeneberg",
email: "daveneberg#example.com",
profile_photo: "http://phontest.lbch.com//users/user1.jpg",
contest_count: "3",
photo_count: 19,
win_count: "0",
photos: [
"images/contest/diwali1.jpg",
"images/contest/diwalc2.jpg",
"images/contest/145043cd811.png",
"images/contest/145043def03411.jpg",
"images/contest/14504ger11.jpg"
]
}
]
}
I tried the following code but values in arrayList_ph is null. I am confused about how to parse this JSON content.
JSONObject object = new JSONObject(json);
JSONArray arr = object.getJSONArray("posts");
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.getJSONObject(index);
user = arr.getJSONObject(0).getString("name");
user_email = arr.getJSONObject(0).getString("email");
user_profile = arr.getJSONObject(0).getString("profile_photo");
user_count = arr.getJSONObject(0).getString("count");
user_photo_count = arr.getJSONObject(0).getInt("photo_count");
contest_count = arr.getJSONObject(0).getString("contest_count");
win_count = arr.getJSONObject(0).getString("win_count");
JSONArray ph_arr= arr.getJSONObject(0).getJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
arrayList_ph.add(ph_arr.getString(in));
}
}
Please help me to parse that field.
Please try this solution.
This solutions is worked for me.
JSONObject object = new JSONObject("");
JSONArray arr = object.optJSONArray("posts");
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.optJSONObject(index);
user = object1.optString("name");
user_email = object1.optString("email");
user_profile = object1.optString("profile_photo");
user_count = object1.optString("count");
user_photo_count = object1.optInt("photo_count");
contest_count = object1.optString("contest_count");
win_count = object1.optString("win_count");
JSONArray ph_arr = object1.optJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
String str = ph_arr.opt(in).toString();
arrayList_ph.add(str);
}
}
change your parsing code to this ,
JSONObject object = new JSONObject(json);
JSONArray arr = object.getJSONArray("posts");
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.getJSONObject(index);
user = object1.getString("name");
user_email = object1.getString("email");
user_profile = object1.getString("profile_photo");
user_count = object1.getString("count");
user_photo_count = object1.getInt("photo_count");
contest_count = object1.getString("contest_count");
win_count = object1.getString("win_count");
JSONArray ph_arr= object1.getJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
String str = ph_arr.get(in).toString();
arrayList_ph.add(str);
}
}
Try -
JSONObject object = new JSONObject(json);
JSONArray arr = object.getJSONArray("posts”);
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.getJSONObject(index);
user = object1.getString("name");
user_email = object1.getString("email");
user_profile = object1.getString("profile_photo");
user_count = object1.getInt("count");
user_photo_count = object1.getInt("photo_count");
contest_count = object1.getString("contest_count");
win_count = object1.getString("win_count");
JSONArray photos_arr= object1.getJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
String str = ph_arr.get(in).toString();
arrayList_ph.add(str);
}
}
Please cross check Following:
1) I think your json response is not properly formatted.
Validate from this: https://jsonformatter.curiousconcept.com/
Your json response should be :
{
"posts":[
{
"count":1,
"user_id":"1",
"name":"Dave Greeneberg",
"email":"daveneberg#example.com",
"profile_photo":"http://phontest.lbch.com//users/user1.jpg",
"contest_count":"3",
"photo_count":19,
"win_count":"0",
"photos":[
{
"image":"images/contest/diwali1.jpg"
},
{
"image":"images/contest/diwalc2.jpg"
},
{
"image":"images/contest/145043cd811.png"
},
{
"image":"images/contest/145043def03411.jpg"
},
{
"image":"images/contest/14504ger11.jpg"
}
]
}
]
}
2) If that still does not work...Try debugging and post your log please...

Categories

Resources