Not able to access JSON - android

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/

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");
}

Decode nested JSON array in 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");
}

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

JSON error while trying to fetch jsonarray

I want to fetch array from json object but get error
When I do jarray2 = object1.getJSONArray(route);
I get the following error
APP CRASH: No value for (the following JSON)
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.42252295423907,
"lng": 4.873809814453125
},
"name": "Coenplein, A10, Amsterdam, Noord, Amsterdam, MRA, Stadsregio Amsterdam, North Holland, Netherlands, 1035RN, The Netherlands",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.28674750920209,
"lng": 4.941873550415039
},
"name": "Holendrechterzijweg, Ouderkerk aan de Amstel, Ouder-Amstel, MRA, Stadsregio Amsterdam, North Holland, Netherlands, 1191LJ, The Netherlands",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.0727536539532,
"lng": 4.32861328125
},
"name": "87, Zwetstraat, Rivierenbuurt, The Hague, MRDH, South Holland, Netherlands, 2515VE, The Netherlands",
"_initHooksCalled": true
}]
Here is the code
try
{
object1 = new JSONObject(response);
jarray1 = object1.getJSONArray("selected_route_data");
for(int i=0;i<jarray1.length();i++)
{
json1 = jarray1.getJSONObject(i);
String route_id = json1.getString("route_id").toString();
String route_name = json1.getString("route_name").toString();
String route = json1.getString("route_data").toString();
jarray2 = object1.getJSONArray(route);
}
}
catch (JSONException e)
{
Log.e("APP CRASH", e.getMessage());
}
It appears the JSON you are attempting to parse does not contain the values you are looking for. None of the elements in the array contain either route_id, route_name or route_data.
You should check if an element exists in the JSON you are parsing, you can do something like
String route_id = null;
if (!json1.optString("route_id").isEmpty()) {
route_id = json1.getString("route_id").toString();
}

Categories

Resources