Decode nested JSON array in Android - android

I have a nested JSON array which I want to decode. I have already found a way to decode a specified info in the object but it's not working so good.
This is the code I used to decode (name, cover and street) from the JSON object:
JSONArray jsonArray = response.getJSONArray("data");
for (int i=0; i < jsonArray.length();i++){
JSONObject events = jsonArray.getJSONObject(i);
String name = events.getString("name");
JSONObject cover = events.getJSONObject("cover");
String imgurl = cover.getString("source");
JSONObject place = events.getJSONObject("place");
JSONObject loc = place.getJSONObject("location");
String street = loc.getString("street");
ItemListView item = new ItemListView(name,street,imgurl);
listItems.add(item);
adapter = new ItemListAdapter(listItems, getActivity());
recyclerView.setAdapter(adapter);
}
I want to decode more info like description, end_time and start_time.
The JSON data structure looks like this:
{
"data": [
{
"description": "",
"end_time": "",
"name": "",
"place": {
"name": "",
"location": {
"city": "",
"country": "",
"latitude": 0000000,
"longitude": 000000,
"street": ""
},
"id": ""
},
"start_time": "",
"id": ""
},
{
"description": "",
"end_time": "",
"name": "",
"place": {
"name": "",
"location": {
"city": "",
"country": "",
"latitude": 0000000,
"longitude": 000000,
"street": ""
},
"id": ""
},
"start_time": "",
"id": ""
}
]
}
I put the decoded info in a ListView in my Android app and that is why I have an adapter and ListView in the code.
Any help is greatly appreciated :)
Thanks in advance.

This is simple you can get other string like this -:
JSONArray jsonArray = response.getJSONArray("data");
for (int i=0; i < jsonArray.length();i++){
JSONObject events = jsonArray.getJSONObject(i);
String description= events.getString("description");
String end_time= events.getString("end_time");
String start_time= events.getString("start_time");
}

Related

Issue in fetching data from nested JSON file

I'm new to android. I have a JSON file with multiple arrays and I'm able to fetch data from the first array and display it in listview (check the first for loop). But i tried to fetch the next array and i didn't get any results(blank screen). I need to display values from "open_days" array. Posted my JSON file and for loop portion.Please check and help me
MainActivity. java
try {
JSONObject jjsonObject =new JSONObject(result);
String getObject = jjsonObject.getString("message");
String getObject1 = jjsonObject.getString("status");
JSONArray getArray = jjsonObject.getJSONArray("favorite_facility_list");
Log.e("message",getObject);
Log.e("status",getObject1);
Log.e("favorite_facility_list",getArray.toString());
for(int i = 0; i < getArray.length(); i++)
{
JSONObject objects = getArray.getJSONObject(i);
String promotion_id = objects.getString("facility_id");
String promotion_image_name = objects.getString("facility_course_name");
String promotion_image_url = objects.getString("icon_image_name");
JSONArray array2=jjsonObject.getJSONArray("open_days");
for(int j=0;j<array2.length();j++)
{
JSONObject obj2=array2.getJSONObject(j);
String openid = obj2.getString("open_days_id");
String openname = obj2.getString("open_days_name");
//
promotionlists promotionlists = new promotionlists();
promotionlists.setFacility_id(promotion_id);
promotionlists.setFacility_course_name(promotion_image_name);
promotionlists.setIcon_image_name(promotion_image_url);
promotionlists.setOpen_days_id(openid);
promotionlists.setOpen_days_name(openname);
promotionArray.add(promotionlists);
adapter= new CustomAdapter(promotionArray,getApplicationContext());
lv.setAdapter(adapter);
}}
JSON file:
{
"status": "1",
"message": "Success",
"favorite_facility_list": [
{
"facility_id": "11",
"facility_course_name": "Facility 2",
"icon_image_name": "3.jpg",
"banner_image_name_list": [
"39.jpg"
],
"address": "test1",
"open_days": [
{
"open_days_id": "5",
"open_days_name": "Thursday"
},
{
"open_days_id": "6",
"open_days_name": "Friday"
},
{
"open_days_id": "8",
"open_days_name": "Sunday"
},
{
"open_days_id": "7",
"open_days_name": "Saturday"
}
],
"open_time_start": "6:8 pm",
"open_time_end": "12:8 pm",
"workouts": [
{
"workout_id": "1",
"workout_name": "Aerobic"
},
{
"workout_id": "2",
"workout_name": "Yoga"
},
{
"workout_id": "4",
"workout_name": "Gym"
},
{
"workout_id": "8",
"workout_name": "Pool"
}
],
"equipments": [
{
"equipment_id": "5",
"equipment_name": "Rowing"
},
{
"equipment_id": "6",
"equipment_name": "Stationary Bike"
},
{
"equipment_id": "7",
"equipment_name": "Bench Press"
},
{
"equipment_id": "8",
"equipment_name": "TRX"
}
],
"services": [
{
"service_id": "4",
"service_name": "Tranning"
},
{
"service_id": "1",
"service_name": "Personal Training"
}
],
"drop_in_rate": [
"10-test",
"20-test1",
"30-test3"
],
"parking_status": "1",
"parking_notes": "2 hrs available",
"facility_status": "1",
"facility_status_description": "Live",
"rating": "2.90",
"distance": "9412.2ml",
"already_like": 1,
"weburl": "",
"phone_no": "",
"facility_lattitude": "-3",
"facility_longitude": "151"
}
]
}
Your Logcat throws JSONException.
Don't
JSONArray array2=jjsonObject.getJSONArray("open_days");
Do
JSONArray array2=objects.getJSONArray("open_days");
You are using the wrong object to fetch open_days
Change
JSONArray array2 = jjsonObject.getJSONArray("open_days");
to
JSONArray array2 = objects.getJSONArray("open_days");

How can i parse objects in arrays in arrays from json

I've been trying to parse the objects from this object that is inside an array inside another array. I made two loops because there are multiple objects that i'm trying to make a list from.
This is what the json looks like
{
"type": "FeatureCollection",
"metadata": {
"generated": 1522105396000,
"url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson",
"title": "USGS Magnitude 4.5+ Earthquakes, Past Day",
"status": 200,
"api": "1.5.8",
"count": 7
},
"features": [{
"type": "Feature",
"properties": {
"mag": 4.7,
"place": "106km SW of Hihifo, Tonga",
"time": 1522100348420,
"updated": 1522102052040,
"tz": -720,
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/us1000d9c6",
"detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/us1000d9c6.geojson",
"felt": null,
"cdi": null,
"mmi": null,
"alert": null,
"status": "reviewed",
"tsunami": 0,
"sig": 340,
"net": "us",
"code": "1000d9c6",
"ids": ",us1000d9c6,",
"sources": ",us,",
"types": ",geoserve,origin,phase-data,",
"nst": null,
"dmin": 3.738,
"rms": 0.85,
"gap": 66,
"magType": "mb",
"type": "earthquake",
"title": "M 4.7 - 106km SW of Hihifo, Tonga"
},
"geometry": {
"type": "Point",
"coordinates": [-174.4796, -16.604, 175.39]
},
"id": "us1000d9c6"
},
{
"type": "Feature",
"properties": {
"mag": 4.8,
"place": "West Chile Rise",
"time": 1522025174820,
"updated": 1522026587040,
"tz": -360,
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/us1000d90k",
"detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/us1000d90k.geojson",
"felt": null,
"cdi": null,
"mmi": null,
"alert": null,
"status": "reviewed",
"tsunami": 0,
"sig": 354,
"net": "us",
"code": "1000d90k",
"ids": ",us1000d90k,",
"sources": ",us,",
"types": ",geoserve,origin,phase-data,",
"nst": null,
"dmin": 9.665,
"rms": 0.87,
"gap": 192,
"magType": "mb",
"type": "earthquake",
"title": "M 4.8 - West Chile Rise"
},
"geometry": {
"type": "Point",
"coordinates": [-86.6644, -41.0452, 10]
},
"id": "us1000d90k"
}
],
"bbox": [-178.6721, -56.8886, 10, 151.396, 56.3364, 541.02]
}
I just need the place, magnitude and time from both arrays but i can't seem to pick the right array to get the object from. ex:(features.properties.place)
List<String> allPlaces = new ArrayList<>();
JSONArray JA = new JSONArray(data);
JSONArray features = JA.getJSONArray(2);
// JSONArray properties = features.getJSONArray(1);
for (int i = 0; i < features.length(); i++){
JSONArray properties = (JSONArray) features.get(i);
for (int j = 0; j < properties.length(); j++){
JSONObject JO = (JSONObject) features.get(i);
String place = JO.getString("place");
singlePlace = "place: " + place;
dataPlace = "" + singlePlace;
allPlaces.add(place);
}
edit1: to be clear, i am able to get information from the first array, so the value of type, but not anything inside of features,
A problem is that you are parsing the properties as a JSONArray but in fact it's a JSONObject. So, you should try this loop to parse needed data:
JSONObject root = new JSONObject(data); //Where `data` is your raw json string
JSONArray features = root.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject properties = features.getJSONObject(i).getJSONObject("properties");
double mag = properties.getDouble("mag");
String place = properties.getString("place");
long time = properties.getLong("time");
}

Not able to access JSON

I'm not able to access the JSON from my file. My JSON file content is:
{
"AuditQuestions": [{
"categoryName": "General",
"QuestionList": [{
"quesId": "01",
"type": "editText",
"questText": "Inspected By",
"answer": ""
},
{
"quesId": "02",
"type": "editText",
"questText": "This Audit Is For City:",
"answer": ""
},
{
"quesId": "03",
"type": "editText",
"questText": "This Audit Is For Property:",
"answer": ""
},
]
},
{
"categoryName": "Accessibility, Location and Security",
"QuestionList": [{
"quesId": "17",
"type": "radio",
"questText": "Could you find the property easily with the address given",
"answer": ["Yes", "No"]
},
{
"quesId": "18",
"type": "editText",
"questText": "Please suggest what we can add to the address to make it more locatable (eg: what landmark?)",
"answer": ""
},
]
}
.
.
.
.
.
.
}]
Each 'QuestionList' has like 10-15 sets, but I have skipped them for simplicity.
My code to access it is:
public void getQuestion(String page) {
questionList = new ArrayList<QuestionList>();
String category;
String quesId ;
String questionType ;
String questionText;
String answer;
try {
JSONObject jsonObj = new JSONObject(page);
JSONArray jssArray = jsonObj.getJSONArray("AuditQuestions");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
category = jsonChildObj.getString("categoryName");
quesId = jsonChildObj.getJSONObject("QuestionList").getString("quesId");
questionType = jsonChildObj.getJSONObject("QuestionList").getString("type");
questionText = jsonChildObj.getJSONObject("QuestionList").getString("questText");
answer = jsonChildObj.getJSONObject("QuestionList").getString("answer");
QuestionList qList = new QuestionList();
qList.setQuesId(quesId);
qList.setQuesText(questionText);
qList.setQuesTypw(questionType);
qList.setAnswer(answer);
qList.setCategoryName(category);
questionList.add(qList);
}
.
.
.
.
.
}
I tried to find if something was wrong with my code. But it looks fine to me.
Please help if there is something wrong with the code I've used above.
Thanks in advance!
Try this
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
category = jsonChildObj.getString("categoryName");
JSONArray jsonArrayQueList = jsonChildObj.getJSONArray("QuestionList");
for(int j = 0 ; j<jsonArrayQueList.length(); j++)
{
JSONObject jsonObjectqueDetail = jsonArrayQueList.getJSONObject(j);
quesId = jsonObjectqueDetail.getString("quesId");
questionType = jsonObjectqueDetail.getString("type");
questionText = jsonObjectqueDetail.getString("questText");
answer = jsonObjectqueDetail.getString("answer");
QuestionList qList = new QuestionList();
qList.setQuesId(quesId);
qList.setQuesText(questionText);
qList.setQuesTypw(questionType);
qList.setAnswer(answer);
qList.setCategoryName(category);
questionList.add(qList);
}
}
First your json should like follow
{
"AuditQuestions":
[
{
"categoryName": "General",
"QuestionList": [
{
"quesId": "01",
"type": "editText",
"questText": "Inspected By",
"answer": ""
},
{
"quesId": "02",
"type": "editText",
"questText": "This Audit Is For City:",
"answer": ""
},
{
"quesId": "03",
"type": "editText",
"questText": "This Audit Is For Property:",
"answer": ""
}]
},
{
"categoryName": "Accessibility, Location and Security",
"QuestionList": [{
"quesId": "17",
"type": "radio",
"questText": "Could you find the property easily with the address given",
"answer": ["Yes", "No"]
},
{
"quesId": "18",
"type": "editText",
"questText": "Please suggest what we can add to the address to make it more locatable (eg: what landmark?)",
"answer": ""
}]
}]
}
Then parse like this. i have parse it and put your questions QuestionList object
try {
JSONObject jsonObj = new JSONObject(input);
JSONArray jssArray = jsonObj.getJSONArray("AuditQuestions");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
category = jsonChildObj.getString("categoryName");
JSONArray jssArray1 = jsonChildObj.getJSONArray("QuestionList");
for (int i1 = 0; i1 < jssArray1.length(); i1++) {
JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1);
questionType = jsonChildObj1.getString("type");
questionText = jsonChildObj1.getString("questText");
answer = jsonChildObj1.getString("answer");
quesId = jsonChildObj1.getString("quesId");
QuestionList qList = new QuestionList();
qList.setQuesId(quesId);
qList.setQuesText(questionText);
qList.setQuesTypw(questionType);
qList.setAnswer(answer);
qList.setCategoryName(category);
questionList.add(qList);
}
}
}catch (JSONException e)
{
e.printStackTrace();
}
First your json data which yo want to parse is wrong.
Try to format your json string and then parse,
Try to add your json data in a jsonviewer and change accordingly.
The jsonviewer link as follows:
http://jsonviewer.stack.hu/

how to get 1st array value

{
"status": "true",
"data": [
{
"giid": "91",
"gid": "26",
"name": "gallery/image/7475068.png",
"type": "0",
"singer": ""
},
{
"giid": "92",
"gid": "25",
"name": "gallery/image/8704185.png",
"type": "0",
"singer": ""
},
{
"giid": "93",
"gid": "25",
"name": "gallery/image/3639377.png",
"type": "0",
"singer": ""
},
{
"giid": "94",
"gid": "25",
"name": "gallery/image/5589478.png",
"type": "0",
"singer": ""
},
{
"giid": "95",
"gid": "25",
"name": "gallery/image/3503162.png",
"type": "0",
"singer": ""
}]}
get only first value in my list view how its possible?
my code :-
try {
JSONArray jsonObject = response.getJSONArray("data");
for (int i = 0; i < jsonObject.length(); i++) {
System.out.println("<<<<<<<<<<<<<<<<<<<");
JSONObject object1 = jsonObject.getJSONObject(i);
Beans_News info = new Beans_News();
info.setDate(object1.getString("giid"));
info.setNews(object1.getString("name"));
info.setNewsid(object1.getString("gid"));
info.setStatus(object1.getString("type"));
array_bean.add(info);
lvls.setAdapter(new CustomAdapter_classwork());
pDialog.hide();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Not available", Toast.LENGTH_SHORT).show();
e.printStackTrace();
pDialog.hide();
}
i want only first value in my list please help me
If you send response like:
res.send({'status':'true', 'data': data})
or
res.json({'status':'true', 'data': data})
and this data is a array then you can get 1st element like
obj = response;
let arr= obj.data;
if(arr.length>0) firstElement = arr[0]
else //whatever you want
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray jArray = jsonObject.getJSONArray("data");
//remove for loop if you only need single data
//for (int i = 0; i < jArray.length(); i++) {
//if you need first value set 0 in index
JSONObject object1 = jArray.getJSONObject(0);
info.setDate(object1.getString("giid"));
info.setNews(object1.getString("name"));
info.setNewsid(object1.getString("gid"));
info.setStatus(object1.getString("type"));
try this hope it helps
Made Changes here
JSONObject object1 = jsonObject.getJSONObject(0);
Use 0 index
update your code like this
JSONObject jsonObject = response.getJSONArray("data").getJSONObject(0);
Beans_News info = new Beans_News();
info.setDate(jsonObject.getString("giid"));
info.setNews(jsonObject.getString("name"));
info.setNewsid(jsonObject.getString("gid"));
info.setStatus(jsonObject.getString("type"));
this is the simplest code you can try to achieve your task.
Just set .getJSONObject(0);
JSONObject object1 = jsonObject.getJSONObject(0); // Set 0 for First Value
Beans_News info = new Beans_News();
info.setDate(object1.getString("giid"));
info.setNews(object1.getString("name"));
info.setNewsid(object1.getString("gid"));
info.setStatus(object1.getString("type"));
.......

How to get a given below value from json data?

I need to get the images array data how to put into the adapter and not required adapter code? Only loop and how to add that's important for me
and then after second I can access option_value array.
First all images can be accessed then after a option_value array.
{
"success": true,
"data": {
"id": "50",
"seo_h1": "",
"name": "Shirt 10001",
"manufacturer": "",
"sku": "",
"model": "10001",
"image": "http://api.yellowskydemo.com/image/cache/data/shirts/7228-500x500.jpg",
"images": [
"http://api.yellowskydemo.com/image/cache/data/shirts/13-500x500.jpg",
"http://api.yellowskydemo.com/image/cache/data/shirts/302-500x500.jpg",
"http://api.yellowskydemo.com/image/cache/data/shirts/5-500x500.jpg",
"http://api.yellowskydemo.com/image/cache/data/shirts/205-500x500.jpg"
],
"price": "$540.00",
"rating": 0,
"description": "<p>Fasten your fashion belts, for this is the ultimate edit of swanky casual wear by Ralph Lauren! For men who are born with a strong sense of style, the American powerhouse packs a colourful punch with this high-fash collection of shirts and sporty, monogrammed polos.</p>\r\n\r\n<p>Fasten your fashion belts, for this is the ultimate edit of swanky casual wear by Ralph Lauren! For men who are born with a strong sense of style, the American powerhouse packs a colourful punch with this high-fash collection of shirts and sporty, monogrammed polos.</p>\r\n",
"attribute_groups": [],
"special": "",
"discounts": [],
"options": [
{
"name": "Size",
"type": "select",
"option_value": [
{
"image": "http://api.yellowskydemo.com/image/cache/no_image-100x100.jpg",
"price": "$50.00",
"price_prefix": "-",
"product_option_value_id": "17",
"option_value_id": "55",
"name": "L-40",
"quantity": "99"
},
{
"image": "http://api.yellowskydemo.com/image/cache/no_image-100x100.jpg",
"price": "$40.00",
"price_prefix": "+",
"product_option_value_id": "18",
"option_value_id": "57",
"name": "XXL-44",
"quantity": "100"
}
],
"required": "1",
"product_option_id": "227",
"option_id": "14"
}
],
"minimum": "1",
"meta_description": "",
"meta_keyword": "",
"tag": "",
"upc": "",
"ean": "",
"jan": "",
"isbn": "",
"mpn": "",
"location": "",
"stock_status": "Out Of Stock",
"manufacturer_id": null,
"tax_class_id": "0",
"date_available": "2014-08-12",
"weight": "0.00000000",
"weight_class_id": "1",
"length": "0.00000000",
"width": "0.00000000",
"height": "0.00000000",
"length_class_id": "1",
"subtract": "0",
"sort_order": "1",
"status": "1",
"date_added": "2014-08-13 12:05:56",
"date_modified": "2015-06-30 11:19:39",
"viewed": "8",
"weight_class": "kg",
"length_class": "cm",
"reward": "0",
"points": "0",
"category": [
{
"name": "Shirts",
"id": "59"
},
{
"name": "Casual Shirts",
"id": "60"
}
],
"quantity": "99",
"reviews": {
"review_total": "0"
}
}
}
You should really look into How to parse JsonObject / JsonArray in android.
Please put your code of also what you have tried because people are here to help solve error/problem not to do coding.
Here is code from which you can Parse your json
JSONObject jsonObject = new JSONObject();
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONArray imagesArray = dataObject.getJSONArray("images");
ArrayList<String> listOfImagesUrl = new ArrayList<>();
for(int i = 0; i < imagesArray.length(); i++)
{
listOfImagesUrl.add(imagesArray.getString(i)); // listOfImages
}
// code for option value
JSONArray optionsArray = dataObject.getJSONArray("options");
for(int i = 0; i < optionsArray.length(); i++)
{
JSONObject option = optionsArray.getJSONObject(i);
JSONArray optionsValueArray = option.getJSONArray("option_value");
for(int j = 0 ; j < optionsValueArray.length(); j++)
{
JSONObject optionValueObject = optionsValueArray.getJSONObject(j);
String image = optionValueObject.getString("image");
String price = optionValueObject.getString("price");
String price_prefix = optionValueObject.getString("price_prefix");
//same like this
}
}

Categories

Resources