how to get 1st array value - android

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

Related

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/

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

JSONArray strange behavior for different API Versions

I have a problem with JSONArray. My JSONArray works on API 22 but not on a device with API less than 22.
When I change my compile sdk I get tons of errors.
Is there any solution for this strange behavior. I can't explain it...
This is the JSON:
{"2":"[{\"id\":\"3\",\"value\":\"1.15\",\"name\":\"Knobi\"}, Dressing]","1":"[{\"id\":\"1\",\"value\":\"0.00\",\"name\":\"Scharf\"}, Soße, {\"id\":\"2\",\"value\":\"1.00\",\"name\":\"Tzatziki\"}, Soße]"}
if(addonsJSON != null)
{
Iterator<String> iterator = addonsJSON.keys();
while (iterator.hasNext())
{
String theKey = iterator.next();
System.out.println(addonsJSON.get(theKey));
JSONArray values = addonsJSON.getJSONArray(theKey);
for (int j = 0; j < values.length(); j+=2)
{
JSONObject vals = new JSONObject(values.getString(j));
CartChild cartChild = new CartChild();
cartChild.name = vals.getString("name");
cartChild.price = vals.getString("value");
itemtotal += Float.parseFloat(vals.getString("value"));
childsList.add(cartChild);
}
}
}
your json is not a valid json text. You can't iterate over invalid json
modify it like that
{
"1": [
{
"id": "1",
"value": "0.00",
"name": "Scharf"
},
"Soße",
{
"id": "2",
"value": "1.00",
"name": "Tzatziki"
},
"Soße"
],
"2": [
{
"id": "3",
"value": "1.15",
"name": "Knobi"
},
"Dressing"
]
}
compare your json and mine on http://jsonlint.com/
The problem was that I convert the HashMap to a JSONObject. After that I saved my JSONObject as a String to SugarORM. The convertion was the fault!
So I tried it with GSON. Now it works.
So just use this:
Gson gson = new Gson();
String json = gson.toJson(hashmap);

Count the json objects inside json Array in Android?

I am trying to parse json values into my Android application. Here i am stuck at a place wherein I need to have the objects length inside the json arraylist.
Below is my json:
"events": { //json object
"2012-11-30": [ // json array
{
"privacy": "OPEN",
"name": "LOGDGE"
}
],
"2013-08-17": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-14": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-27": [
{
"privacy": "OPEN",
"name": "Salsa Party!"
}
{
"privacy": "OPEN",
"name": "Dance Performance Course",
}
],
"2013-10-23": [
{
"privacy": "OPEN",
"name": "Dance Performance Course"
}
]
}
Now my question is how do I parse to get the length of the json array like:
2012-11-30 count = 1
2013-08-17 count = 1
2013-09-27 count = 2
How do I loop the json array using the date's as they are json object and find the length of each of the json array dates. I want count of each array individually over here.
Would I need to add a key value kind of pair in the json array "dates" so as I can have a for loop to get the count of the values inside the array?
Thank you in advance
Try Below Code and count objects using length of JsonArray:
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String key = keys.next();
try{
JSONArray array = jObject.getJSONArray(key);
//count objects values using array length.
}
catch(Exception e){
e.printStackTrace()
}
}
String jstr = jso.getString("Events");
JSONObject mdcalkey = new JSONObject(jstr);
Iterator iter = mdcalkey.keys();
ArrayList<String> arr = new ArrayList<String>();
ArrayList<String> arrTimeDate = new ArrayList<String>();
ArrayList<String> arrtype = new ArrayList<String>();
while (iter.hasNext()) {
arr.add((String) iter.next());
}
// ja = mdcalkey.getJSONArray(arr.get(0));
jar = new JSONArray[arr.size()];
This arr array will display all dates array..please check it..if any query then tell me.
You can iterate over the keys in your JSONObject and check if their corresponding values are JSONArrays, then store their lengths in a map:
Iterator iter = yourJSONObject.keys();
while (iter.hasNext())
{
String key = (String) iter.next();
JSONArray array = yourJSONObject.optJSONArray(key);
if (array != null)
{
// the value for this key is an array
for (int i = 0; i < array.length; i++){
// do stuff
}
}
}
String json = "events": { //json object
"2012-11-30": [ // json array
{
"privacy": "OPEN",
"name": "LOGDGE"
}
],
"2013-08-17": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-14": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-27": [
{
"privacy": "OPEN",
"name": "Salsa Party!"
}
{
"privacy": "OPEN",
"name": "Dance Performance Course",
}
],
"2013-10-23": [
{
"privacy": "OPEN",
"name": "Dance Performance Course"
}
]
}
try {
JSONObject obj = new getJSONObject(new JSONObject("{"+"json"+"}").getJSONObject("events").toString());
Iterator iterator = obj.keys();
while (iterator.hasNext())
{
String key = (String) iterator.next();
JSONArray array = obj.optJSONArray(key);
if (array != null)
{
// the value for this key is an array
for (int i = 0; i < array.length; i++){
// do stuff
}
}
}
}
catch (JSONException e)
{
// handle exception here
}

Categories

Resources