Parsing JSON in Android using AsyncHttpClient - android

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

Related

JSONarray separation to lists in android

I have the following JSONarray and I need to have the output like below. Help please.
{
"data": [
{
"Mandal": "Rambilli",
"Village": "Chatametta"
},
{
"Mandal": "Anakapalle",
"Village": "Valluru"
},
{
"Mandal": "Anakapalle",
"Village": "Venkupalem"
},
{
"Mandal": "Rambilli",
"Village": "Chebrolu Konda"
},
{
"Mandal": "Anakapalle",
"Village": "Vetajangalapalem"
},
{
"Mandal": "Anakapalle",
"Village": "Vooderu"
}
]
}
The out put needs to be two lists with names of Mandal
List<String> Rambilli to contain [Chatametta, Chebrolu Konda]
List Anakapalle to contain [Valluru, Venkupalem, Vetajangalapalem, Vooderu]
The major roadblock I'm facing is how to put the name of the mandal to the output list.
I hard coded every thing but Try:
List<String> listOfRambilli = new ArrayList<>();
List<String> listOfAnakapalle = new ArrayList<>();
try {
JSONArray dataArray = jsonData.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject objectInsideDataArray = dataArray.getJSONObject(i);
String village = objectInsideDataArray.getString("Village");
String mandal = objectInsideDataArray.getString("Mandal");
if (mandal.equals("Rambilli"))
listOfRambilli.add(village);
else if (mandal.equals("Anakapalle"))
listOfAnakapalle.add(village);
else
throw new NoSuchElementException();
}
Log.d("TAG", "" + listOfAnakapalle);
Log.d("TAG", "" + listOfRambilli);
} catch (JSONException e) {
e.printStackTrace();
}
Try this way:
JSONArray jsonArray = jsonObject.getJSONArray("data");
ArrayList<String> rambilliList = new ArrayList<>();
ArrayList<String> anakapalleList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject listJsonObject = jsonArray.getJSONObject(i);
if(listJsonObject.getString("Mandal").equals("Rambilli")){
rambilliList.add(listJsonObject.getString("Village"));
} else if(listJsonObject.getString("Mandal").equals("Anakapalle")) {
anakapalleList.add(listJsonObject.getString("Village"));
}
}
System.out.println("Rambilli contains" + rambilliList)
System.out.println("Anakapalle contains" + anakapalleList)

Can not parse this multilevel json data

I am getting null pointer error while converting string to json object i have tried gson,parser etc but none seems to be working.
Can somebody provide a solution for below response (I have done substring in order to remove "data: "):
data: {
"C": "abc",
"A": [{
"B": "BcastHub",
"C": "onData",
"D": [{
"ID": "1",
"One": [{
"Plus": 5.0,
"Minus": 93400.0
}, {
"Plus": 4.9,
"Minus": 8570.0
}, {
"Plus": 4.8,
"Minus": 140606.0
}],
"Two": [{
"Plus": 5.1,
"Minus": 34.0
}, {
"Plus": 5.2,
"Minus": 44622.0
}, {
"Plus": 5.3,
"Minus": 2408.0
}]
}]
}]
}
My code for Fetching
try{
URL urlData = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlData.openConnection().getInputStream(), "utf-8"));
String struct = reader.readLine();
while ((struct = reader.readLine()) != null ) {
if(!struct.equals("")) {
struct = struct.substring(6,struct.length());
JSONParser parser = new JSONParser();
JSONObject lev1 =(JSONObject) parser.parse(struct);
//JSONObject lev1 = (JSONObject) obj;
JSONObject parent = (JSONObject) lev1.get("A");
for(int j=0;j<parent.length();j++) {
JSONObject child1 = (JSONObject) parent.get("D");
JSONArray child2 = (JSONArray) child1.get("One");
for (int i = 0; i < child2.length(); i++) {
JSONObject item = child2.getJSONObject(i);
final String plus = item.getString("Plus");
final String minus = item.getString("Minus");
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Plus => " + plus + "Minus = > " + minus);
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Tell me if you want anything else. Thanks.
Edit : I am trimming the start of the string in order to make it in proper format and then converting the string to JSONObject is giving me error. at JSONObject parent = (JSONObject) lev1.get("A"); as lev1 is null.
try {
jsonResponse = new JSONObject(strJson2);
JSONObject user = jsonResponse.getJSONObject("data");
num = user.getString("C");
JSONArray user1 = user.getJSONArray("A");
for (int i = 0; i < user1.length(); i++) {
jsonChildNode = user1.getJSONObject(i);
String B = jsonChildNode.getString("B");
String c2 = jsonChildNode.getString("C");
Toast.makeText(this, B + "::" + c2.toString(), Toast.LENGTH_SHORT).show();
JSONArray jsonArraysunject = jsonChildNode.getJSONArray("D");
for (int j = 0; j < jsonArraysunject.length(); j++) {
JSONObject DD = jsonArraysunject.getJSONObject(j);
String dd = DD.getString("ID");
Toast.makeText(this, dd.toString(), Toast.LENGTH_SHORT).show();
One = DD.getJSONArray("One");
for (int k = 0; k < One.length(); k++) {
// for (int i = 0; i < lengthJsonArr; i++) {
jsonChildNodeo = One.getJSONObject(k);
type = jsonChildNodeo.getString("Plus");
num = jsonChildNodeo.getString("Minus");
makeText.add("Plus - " + type);
makeText.add("Minus - " + num);
Toast.makeText(this, makeText.toString(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "hdjeh", Toast.LENGTH_SHORT).show();
Two = jsonChildNodeo.getJSONArray("Two");
Toast.makeText(this, Two.toString(), Toast.LENGTH_SHORT).show();
for (int r = 0; r < Two.length(); r++) {
JSONObject tw = Two.getJSONObject(r);
String tplus = tw.getString("Plus");
String tminus = tw.getString("Minus");
makeText2.add("plus - " + tplus);
makeText2.add("minus - " + tminus);
Toast.makeText(this, makeText2.toString(), Toast.LENGTH_SHORT).show();
// }
}
}
Just place your json data in jsonString vairable and that's all.
try {
JSONObject mainObject=new JSONObject(jsonString);
System.out.println(mainObject.toString());
System.out.println("// First Level object(s)");
System.out.println("C--> "+mainObject.getString("C"));// First Level object C
JSONArray firstArray=mainObject.getJSONArray("A");
for(int i=0;i<firstArray.length();i++){ //First Level Array A
JSONObject arrayObject =firstArray.getJSONObject(i);
System.out.println("// Second Level object(s)");
System.out.println("B--> "+arrayObject.getString("B")); // Second Level Object B
System.out.println("C--> "+arrayObject.getString("C")); // Second Level Object C
System.out.println("//Second Level Array D");
JSONArray secondLevelArray=arrayObject.getJSONArray("D");
for(int j=0;j<secondLevelArray.length();j++){
JSONObject innerArrayObject=secondLevelArray.getJSONObject(j);
System.out.println("// Third Level object(s) ");
System.out.println("ID --> "+innerArrayObject.getString("ID"));
JSONArray thirlLevelArray1=innerArrayObject.getJSONArray("One");
for(int k=0;k<thirlLevelArray1.length();k++){
JSONObject innerMostObjects=thirlLevelArray1.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
JSONArray thirlLevelArray2=innerArrayObject.getJSONArray("Two");
for(int k=0;k<thirlLevelArray2.length();k++){
JSONObject innerMostObjects=thirlLevelArray2.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I parsed your data using Gson. The advantages of Gson are discussed previously. In addition, you can check goals of Gson.
Here is how to parse your data using Gson:
Note that I have not used code formatting standards (for example, the name of a class should use CamelCase) because you couldn't share real data.
Extracting JSON string:
While extracting JSON string use indexOf(int) instead of hard-coded 6.
jsonString = jsonString.substring(jsonString.indexOf("{"));
Parsing:
Gson gson = new Gson();
data d = gson.fromJson(reader, data.class);
for (a a1 : d.A) {
for (plusminus pm : a1.D[0].One) {
System.out.println("Plus => " + pm.Plus + " Minus => " + pm.Minus);
}
}
Required Classes:
public class data {
public String C;
public a A[];
}
public class a {
public String B;
public String C;
public d D[];
}
public class d {
public int ID;
public plusminus One[], Two[];
}
public class plusminus {
public double Plus;
public double Minus;
}

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.

How to parse JSON in Android Iam using Volley library?

{
"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

Categories

Resources