How to parse JSON Array inside another JSON Array in Android - android

Please, please help me..
I am working on a project and I am getting data from web-services in JSON format. I am trying to parse it but, I am unable to do it. I have this json-data-
{
"response": {
"status": {
"code": "1",
"message": "sucess",
"user_id": "1"
},
"foods": [
{
"char": "A",
"content": [
{
"food_name": "add Malt"
},
{
"food_name": "a la mode"
},
{
"food_name": "Almonds"
}
]
},
{
"char": "Z",
"content": [
{
"food_name": "Zebra Cakes"
},
{
"food_name": "Zucchini, Baby"
},
{
"food_name": "zxc"
}
]
}
]
}
}
From here I am successfully able to get "foods" Array but I am getting stuck when I am trying to get "content" array and food_name data.
I am using this code but I did not get any solution, please check this snip code.
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method","eat_tracking_details"));
nameValuePairs.add(new BasicNameValuePair("uid",userid));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(JSONParser.urlname,"GET", nameValuePairs);
//System.out.println("****json*"+json);
if (json != null) {
try {
JSONObject response = json.getJSONObject("response");
JSONObject status = response.getJSONObject("status");
code = status.getString("code");
JSONArray FoodArray = response.getJSONArray("foods");
for (int i = 0; i < FoodArray.length(); i++) {
String character = FoodArray.getJSONObject(i).getString("char");
System.out.println("*****character****************"+character);
JSONArray FoodNameArray = new JSONArray(FoodArray.getJSONObject(i).getString("content"));
System.out.println("====================///////////"+FoodNameArray);
for (int j = 0; j <FoodNameArray.length(); j++) {
String Foodname = FoodArray.getJSONObject(j).getString("food_name");
System.out.println("#############"+Foodname);
}
}
} catch (JSONException e) {
// TODO: handle exception
}
}
Check this url for web-service response-
WEB-SERVICE URL

You need to replace your respective part of code with this code:
for (int j = 0; j < FoodNameArray.length(); j++) {
String Foodname = FoodNameArray.getJSONObject(j).getString("food_name");
System.out.println("#############" + Foodname);
}

I believe the best approach would use of GSON library (http://code.google.com/p/google-gson/) . In that case you just have to make your model classes and don't worry about the parsing logic.

Related

How to get the json array

I want the array of custac from the given json data. But I dont know how to call custac from that. I want to get the custac values in an array. can anyone help
Here is my code
ArrayList<CustomerPayment> customerPayments = new
ArrayList<CustomerPayment>();
try {
JSONArray resultVal = response.getJSONArray("Data");
int count=resultVal.length();
for(int i=0;i<count;i++)
{
CustomerPayment payment = new CustomerPayment(resultVal.getJSONObject(i));
customerPayments.add(payment);
}
} catch (JSONException e) {
e.printStackTrace();
}
Here is my jsondata
Result: {
"Result": {
"Status": 200,
"Success": true,
"Reason": "OK"
},
"Data": [
{
"CustomerID": "PTM_103",
"FirstName": "Dhanya",
"LastName": "Jacob ",
"NickName": "",
"FundAmount": 440,
"custac": [
{
"AccountTrackingId": "prod_4",
"ReferenceID": "",
"CustomerID": "PTM_103",
"OrderID": "ae3208287743908eb8e5911d8e7e73df",
"orderAmount": "0",
"CreatedAt": "prod"
}
]
},
...
you have to make something like this
JSONObject jsonObject = new JSONObject(response);
JSONArray resultVal = jsonObject.getJSONArray("Data");
JSON data are objects parsed into a string for mostly NoSQL purposes and they can be parsed into objects. Gson is one of the libraries which is easy to use to parse your JSON data.
If you get jsonData as the response string which has Data, the following code can parse the custac in the list of array. But, firstly you have to create an object for Data
Data[] dataCollection = new Gson().fromJson(json,Data[].class);
Data must contain the attributes like CustomerID, FirstName, etc.
For your case,
class Data{
private String CustomerID;
private String FirstName;
private String LastName;
private String NickName;
private int FundAmount;
private ArrayList<Custac> custac;
class Custac{
// Write your attributes as shown above.
}
}
Try This Code
JSONArray custac;
try {
JSONArray resultVal = jsonObject.getJSONArray("Data");
for (int i = 0; i < resultVal.length() - 1; i++) {
jsonObject = resultVal.getJSONObject(i);
custac = jsonObject.getJSONArray("custac");
Log.d("TAG, custac + "");
}
} catch (JSONException e) {
e.printStackTrace();
}

Android parse json force stopped

I am parsing a json url: http://www.json-generator.com/api/json/get/bQmwsOmYeq?indent=2 but I failed to make it happen. I am getting an error. What's wrong with this code?
public void parseJsonResponse(String result) {
Log.i(TAG, result);
pageCount++;
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
CountryInfor country = new CountryInfor();
country.setId(jObject.getString("id"));
country.setName(jObject.getString("name"));
countries.add(country);
}
adapter.notifyDataSetChanged();
if (dialog != null) {
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Replace
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
these two lines by
JSONArray jArray = new JSONArray(result);
Also change
country.setId(jObject.getString("id"));
by
country.setId(jObject.getInt("id") + "");
Because id is of type int not a String.
And it will work fine.
You are getting response like
[
{
"id": ​1,
"name": "Vietnam"
},
{
"id": ​2,
"name": "China"
},
{
"id": ​3,
"name": "USA"
},
{
"id": ​4,
"name": "England"
},
{
"id": ​10,
"name": "Russia"
}
]
So the response is JSONArray and not JSONObject.
Hope it'll help.
Edit
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
if(loadJSON(this.url) != null) {
return loadJSON(this.url).toString();
}
Log.d("LoadJSONFromUrl", "Failed to get JSONObject.");
return null;
}
You are getting JSONObject null, so the error is.
- You should know what is NullPointerException
the issue is with this line
JSONArray jArray = json.getJSONArray("name");
There is no array with name name. it is failing here. Correct this part to obtain the array properly. Rest looks fine.

How to fetch nested json array response like below in android?

how can I fetch this response from URL in android?
1. //main array
[
//array in main array
[
//object in inner array
{
//data to be fetched here
"user_id": "8035",
"sr_no": "MG2459",
"user_type": "2",
"name": "Allen"
}
],
//2nd array in main array
[
{
"user_id": "8035",
"sr_no": "MG2459",
"user_type": "2",
"name": "TestName"
}
]
]
try below code :-
try {
JSONArray ja = new JSONArray(ur string);
for (int i = 0; i < ja.length(); i++)
{
JSONArray ja1 = ja.getJSONArray(i);
for (int j = 0; j < ja1.length(); j++) {
JSONObject jo = ja1.getJSONObject(j);
String user_id = jo.getString("user_id");
String sr_no = jo.getString("sr_no");
String user_type = jo.getString("user_type");
String name = jo.getString("name");
}
}
} catch (Exception e) {
// TODO: handle exception
}

Json parsing in an Android application

I am new in Json parsing. I am receiving Json data from my url which is given below:
[
[
{
"message": "hdjcjcjjckckckckvkckckck",
"timetoken": 14151866297757284
},
{
"message": "ufjfjfjcjfjchfjdhwjroritkgjcj",
"timetoken": 14151869212145692
},
{
"message": "udjfjfudjcyshdhsnfkfkvkf",
"timetoken": 14151869317015766
},
{
"message": "lvkifjsywjfwhsjvjdjfudjgidufkg",
"timetoken": 14151869404695072
},
{
"message": "ifjfydncydhsxhshfjdjejtlfudj",
"timetoken": 14151869494732788
},
{
"message": "22637485969473849506&#&#*%-&+",
"timetoken": 14151869589393336
},
{
"message": "jcjfjdueywjfusufig",
"timetoken": 14151869671994892
},
{
"message": "ofkdiriflfkkkfkdiidk",
"timetoken": 14151869775170644
},
{
"message": "testing",
"timetoken": 14151869895179728
},
{
"message": 1234567,
"timetoken": 14151869986900556
},
{
"message": 9877653,
"timetoken": 14151870106439620
},
{
"message": "zxcvbnmmkljgdaqerip",
"timetoken": 14151870236042386
}
],
14151866297757284,
14151870236042386
]
I am using this to break JsonArray data into different index like I want to display message and timetoken in separate lines in my activity, like this:
message: hdjcjcjjckckckckvkckckck
time token: 14151866297757284
message: 22637485969473849506&#&#*%-&+
time token: 14151869212145693
What should I have to do in the following line of codes:
JSONArray jsonObj = new JSONArray(message.toString()); //message.toString() is the Json Response data
for (int i = 0; i < jsonObj.length(); i++) {
}
I want to display it in my Textview as described above.
Try this one (not tested):
JSONArray jsonObj = new JSONArray(message.toString()); //message.toString() is the Json Response data
JSONArray array = jsonObj.getJSONArray(0);
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String mesage = item.getJsonString("message");
String timespan = item.getJsonString("timespan");
}
you should put json parsing into try-catch block:
try{
JSONArray res = new JSONArray(response.toString());
JSONArray jsonArray = res.getJSONArray(0);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String message = object.getString("message");
String token = object.getString("timetoken");
}
}catch(Exception e){
e.printStackTrace();
}
you have a double array, so you have two JSONArray. Actually, JSONArray usually marked by [] and JSONObject marked by {}.
In other words {}=JSONObject and []=JSONArray.
I have solved the problem. Actually the Json string has double Json Array and then Json Object.
I was doing a mistake to send an object of Json Array to Json Object. Now I have make an object of Json Array1 then send it to Json Array2 and then send the object of Json Array2 in Json Object.
The code is given below:
try {
JSONArray jsonObj = new JSONArray(message.toString());
JSONArray jArray = new JSONArray(jsonObj.get(0).toString());
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
String messageString=c.getString("message");
String timeString=c.getString("timetoken");
String abc = timeString;
}
}

Nested JSON arrays

I am parsing some JSON that has arrays within arrays, and I just cant seem to get the data of the arrays within the first array.
My JSON looks like this (I cut it off in the end so it wasn't that long):
{"TrackingInformationResponse": {
"shipments": [
{
"shipmentId": "03015035146308",
"uri": "\/ntt-service-rest\/api\/shipment\/03015035146308\/0",
"assessedNumberOfItems": 1,
"deliveryDate": "2013-05-13T11:47:00",
"estimatedTimeOfArrival": "2013-05-13T16:00:00",
"service": {
"code": "88",
"name": "DPD"
},
"consignor": {
"name": "Webhallen Danmark ApS",
"address": {
"street1": "Elsa Brändströms Gata 52",
"city": "HÄGERSTEN",
"countryCode": "SWE",
"country": "Sverige",
"postCode": "12952"
}
},
"consignee": {
"name": "Lene Bjerre Kontor & IT Service",
"address": {
"street1": "Lene Bjerre",
"street2": "Ørbækvej 8, Hoven",
"city": "TARM",
"countryCode": "???",
"postCode": "6880"
}
},
"statusText": {
"header": "Forsendelsen er udleveret",
"body": "Forsendelsen blev leveret 13-05-2013 kl. 11:47"
},
"status": "DELIVERED",
"totalWeight": {
"value": "0.55",
"unit": "kg"
},
"totalVolume": {
"value": "0.005",
"unit": "m3"
},
"items": [
{
"itemId": "03015035146308",
"dropOffDate": "2013-05-08T17:18:00",
"deliveryDate": "2013-05-13T11:47:00",
"status": "DELIVERED",
"statusText": {
"header": "Forsendelsen er udleveret til modtageren",
"body": "Forsendelsen blev udleveret 13-05-2013 kl. 11:47"
},
I can get the content of the "shipments" array just fine, but I have no idea how to get the contents of the "items" array. My code looks like this:
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
How would I do the same with the "items" array as I did with the "shipments" array?
You have to get the items array from inside the Shipment array, like you did the shipments, then iterate through that, like you did the shipments.
It might look something like:
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items");
//get items stuff
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
items is a JSON Array located inside the shipments array, so you need to get the items array within the shipments, maybe like this :
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items"));
//iterate over items
}
Hope this helps, Good luck
Try bellow code:
JSONObject jObject = new JSONObject(yourJSONString);
JSONObject trackInfo = jObject.getJSONObject("TrackingInformationResponse");
JSONArray shipMents = trackInfo.getJSONArray("shipments");
JSONArray items = shipMents.getJSONArray("items");

Categories

Resources