JSONObject parsing error when there is no value - android

I have a JSON which looks like this:
{
"notifications": {
"0": {
"id": "27429",
"uID": "6967",
"text": "Text 1"
},
"1": {
"id": "27317",
"uID": "6967",
"text": "Text 2"
},
"2": {
"id": "27315",
"uID": "6967",
"text": "Text 3"
},
"3": {
"id": "27314",
"uID": "6967",
"text": "Text 4"
},
"4": {
"id": "27312",
"uID": "6967",
"text": "Text 5"
}
}
}
I'm taking out "text" string from the response, for this my code looks like this:
JSONObject rootObj = new JSONObject(result);
JSONObject jSearchData = rootObj.getJSONObject("notifications");
int maxlimit = 4;
for (int i = 0; i < maxlimit; i++) {
JSONObject jNotification0 = jSearchData.getJSONObject("" + i + "");
String text = jNotification0.getString("text");
System.out.println("Text: " + text);
}
For now this works perfectly fine, I get all the 4 "text" in the logs.
Now, my problem is that when I get response from server with only 1 or 2 data, something like this:
{
"notifications": {
"0": {
"id": "27429",
"uID": "6967",
"text": "Only one text here"
}
}
}
Then my above logic fails, I get exception stating org.json.JSONException: No value for 1
How can I overcome this problem.
Any kind of help will be appreciated.

you can test if a key exists with rootObj.has("1") or use rootObj.optJSONObject("1");
the former returns true if this object has a mapping for name. The latter returns the value mapped by name if it exists and is a JSONObject, null otherwise.
Or you can interate through the keys inside rootObj, this way:
Iterator<String> keys = jSearchData.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jNotification0 = jSearchData.optJSONObject(key);
if (jNotification0 != null) {
String text = jNotification0.getString("text");
String uID = jNotification0.getString("uID");
String id = jNotification0.getString("id");
}
}

Edit: This is wrong, I read to fast and did not realize jSearchData was an object and not an array. But in my opinion if would make a lot more sense if it was in fact an array instead of an object.
There's no need to hard code the 4. Just take the length of the array and loop through it, like this:
for (int i = 0; i < jSearchData.length(); i++) {
JSONObject jNotification0 = jSearchData.getJSONObject("" + i + "");
String text = jNotification0.getString("text");
System.out.println("Text: " + text);
}

Related

How to get json array data without key name

This is my json data i want to get the first_movie name in top headder and rest of data under that and same as well other work also
{
"actors": [
{
"name": "Amitabh Bachchan",
"age": 76,
"bollywood": true,
"img": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Amitabh_Bachchan_2014.jpg/220px-Amitabh_Bachchan_2014.jpg",
"notablework": [
{
"first_movie": "Saat Hindustani"
},
"Anand(1971)",
"Zanjeer(1973)",
"Sholay(1975)",
"Don(1978)",
"Agneepath(1990)",
"Black(2005)",
"Paa(2009)",
"Piku(2016)"
],
"other_work": [
"Politics",
"Television appearances",
"Voice-acting",
"Humanitarian causes",
"Business investments"
]
},
{
"name": "Salman Khan",
"age": 53,
"bollywood": true,
"img": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Salman_Khan_at_Renault_Star_Guild_Awards.jpg/220px-Salman_Khan_at_Renault_Star_Guild_Awards.jpg",
"notablework": [
{
"first_movie": "Biwi Ho To Aisi"
},
" Biwi Ho To Aisi (1988)",
"Maine Pyar Kiya (1989)",
" Hum Aapke Hain Koun..! (1994)",
" Karan Arjun (1995)"
],
"other_work": [
"Television",
"Brand endorsements"
]
},click here to view my design that i want to show this data
I think you shared two json objects Only as i understand.
Your JSON
{
"actors":[
{
"name":"Amitabh Bachchan",
"age":76,
"bollywood":true,
"img":"https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Amitabh_Bachchan_2014.jpg/220px-Amitabh_Bachchan_2014.jpg",
"notablework":[
{
"first_movie":"Saat Hindustani"
},
"Anand(1971)",
"Zanjeer(1973)",
"Sholay(1975)",
"Don(1978)",
"Agneepath(1990)",
"Black(2005)",
"Paa(2009)",
"Piku(2016)"
],
"other_work":[
"Politics",
"Television appearances",
"Voice-acting",
"Humanitarian causes",
"Business investments"
]
},
{
"name":"Salman Khan",
"age":53,
"bollywood":true,
"img":"https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Salman_Khan_at_Renault_Star_Guild_Awards.jpg/220px-Salman_Khan_at_Renault_Star_Guild_Awards.jpg",
"notablework":[
{
"first_movie":"Biwi Ho To Aisi"
},
" Biwi Ho To Aisi (1988)",
"Maine Pyar Kiya (1989)",
" Hum Aapke Hain Koun..! (1994)",
" Karan Arjun (1995)"
],
"other_work":[
"Television",
"Brand endorsements"
]
}
]
}
Here we process the above data
JSONObject json_obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray actorsArray = json_obj.getJSONArray("actors");
//now looping through all the elements of the json array
for (int i = 0; i < actorsArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject actorsObject = actorsArray.getJSONObject(i);
String actorsName = actorsObject.getString("name");
//Here you can get same like your remaining string data by using json key -> age,bollywood,img
//now we can process notablework object
JSONArray notableworkArray = actorsObject.getJSONArray("notablework");
// now we need another loop for get notable data
for (int j = 0; j < notableworkArray.length(); j++) {
if(j==0) {
JSONObject notableworObject = notableworkArray.getJSONObject(0);
String first_movie = notableworObject.getString("first_movie");
}
}
}

Don't know how to get description from OpenWeatherMap api, only the place and temperature

I've been working on making a simple weather app that displays the temperature, a description of the weather and the location. I'm able to get the location but can't figure out how to get the description of the weather from OpenWeatherMap and it's been bugging me for a few hours now. This is the part of the code in which I have this information laid out:
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherDatas = new JSONObject(jsonObject.getString("main"));
double temperature = Double.parseDouble(weatherDatas.getString("temp"));
int tempIn = (int) (temperature*1.8-459.67);
String placeName = (String) jsonObject.get("name");
MainActivity.tempeartureTextView.setText("" + tempIn);
MainActivity.placeTextView.setText(placeName);
Log.i("it made it", "to end of DownloadTask");
//using http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b1b15e88fa797225412429c1c50c122a1 with zip code
} catch (Exception e) {
e.printStackTrace();
}
}
But for the life of me I cannot figure out how to get the description.
The rest of the code is all here: MainActivity: http://pastebin.com/e2NtTSiP
DownloadTask: http://pastebin.com/ScEREz52
I followed a youtube tutorial on this so I don't quite understand everything but I kinda wanna just do it over and over again till I can get it right.
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
MainActivity.descriptionTextView.setText(description);
}
This fixed it for me!
if your JSON response is following :
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"base": "stations",
"main": {
"temp": 277.14,
"pressure": 1025,
"humidity": 86,
"temp_min": 275.15,
"temp_max": 279.15
},
"visibility": 16093,
"wind": {
"speed": 1.67,
"deg": 53.0005
},
"clouds": {
"all": 1
},
"dt": 1485788160,
"sys": {
"type": 1,
"id": 471,
"message": 0.0116,
"country": "US",
"sunrise": 1485789140,
"sunset": 1485826300
},
"id": 5375480,
"name": "Mountain View",
"cod": 200
}
In order to get weather description from the response,
get "weather" array
for each JSON object present inside weather array, get the "description" property of the JSON object
JSONObject obj = new JSONObject(response);
JSONArray arr = obj.getJSONArray("weather");
for (int i = 0; i < arr.length(); i++) {
JSONObject each = arr.get(i);
each.getString("description");
}

How can I parse string from PHP on ANDROID if my string has no starting value?

Let's assume that I have a string from the PHP request like this.
[
{
"id": "1",
"title": "\"Shaira Casandra Libao, the new PSSC President!\"",
"content": "\"Leadership is the key of success\" - Ms. Libao said.\n\nShaira Casandra Libao won the 75% of the vote. ", "penname": "John Ranniel A. Sinel", "date_send": "2015-01-02",
"sender": "John Ranniel Almendares Sinel",
"shortdesc": "The new PSSC President",
"lang": null
}
,
{
"id": "2",
"title": "\"Merleen Mercolita is now the new leader of LGBT community\"",
"content": "\"Being gay is not bad, it's just on man's judgmental mind..\" Ms. Mercolita said during her presscon wherein she admitted that she is a transwomen.",
"penname": "Shaira Casandra Libao",
"date_send": "2015-02-04",
"sender": "Shaira Boncato Libao",
"shortdesc": "LGBT on the go",
"lang": null
}
]
And I want to display only the title key of the first article on the string.
My code in android is:
//The string result variable is the value given by the onPostExecute() method
String title = "";
JSONObject jsonRootObj = new JSONObject(result);
JSONArray jsonArray = jsonRootObj.optJSONArray(whatamIgannaputOnIt);
JSONObject jsonObject = jsonArray.getJSONObject(0);
title = jsonObject.getString("title");
this.kemb.setText(title);
If I have a string like this:
{
"Data":
[
{
"id": "1",
"title": "\"Shaira Casandra Libao, the new PSSC President!\"",
"content": "\"Leadership is the key of success\" - Ms. Libao said.\n\nShaira Casandra Libao won the 75% of the vote. ", "penname": "John Ranniel A. Sinel", "date_send": "2015-01-02",
"sender": "John Ranniel Almendares Sinel",
"shortdesc": "The new PSSC President",
"lang": null
}
,
{
"id": "2",
"title": "\"Merleen Mercolita is now the new leader of LGBT community\"",
"content": "\"Being gay is not bad, it's just on man's judgmental mind..\" Ms. Mercolita said during her presscon wherein she admitted that she is a transwomen.",
"penname": "Shaira Casandra Libao",
"date_send": "2015-02-04",
"sender": "Shaira Boncato Libao",
"shortdesc": "LGBT on the go",
"lang": null
}
]
}
I can supply the JSONArray jsonArray = jsonRootObj.optJSONArray(whatamIgannaputOnIt); whatamIgannaputOnIt variable the string "Data" but on my case, I don't have that! What I have is the string on the top most of my question. So how can I get the correct output with that kind of string?
First, provided JSON String is JSONArray of JSONObject's
So, instead of getting JSONObject from string get JSONArray :
JSONArray jsonRootObj = new JSONArray(result);
Because jsonRootObj JSONArray contains only single JSONObject which is at 0 index, so use 0 to get JSONObject:
JSONObject jsonObj = jsonRootObj.getJSONObject(0);
String title = jsonObj.optString("title");
if jsonRootObj JSONArray contains more then one JSONObject then iterate over jsonRootObj to get title from all JSONObject's
I'm not sure I understand your question but you should do
JSONArray jsonArray = new JSONArray(result);
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
}

Parsing JSON response without an array name

[
{
"stDescription": "END N/A",
"stCategory": "6",
"sZone": "#",
"sIncident": "0"
},
{
"stDescription": "BEG N/A",
"stCategory": "6",
"sZone": "#",
"sIncident": "0"
},
{
"stDescription": "",
"stCategory": "Null",
"sZone": "4",
"sIncident": "0"
},
{
"stDescription": "",
"stCategory": "Null",
"sZone": "5",
"sIncident": "0"
}
]
There is no array name here, but I want to parse whole array (my JSON parser works fine if I'm using array name).
For parsing this type of JSON...
First store it in String..
and then do following process...
String str = "JSON STRING";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String stDescription = obj.getString("stDescription");
String stCategory= obj.getString("stCategory");
//and other fields
System.out.println(stDescription);
System.out.println(stCategory);
}
This may help you...

Fetch value from JSON in android

I am sending request to the server and it gives me a response and giving data in JSON formats, now i want to fetch some specific value from that JSON format, so hot to do it.
{
"education": [
{
"school": {
"id": "2009305",
"name": "FG boys public high school Bannu Cantt "
},
"type": "High School"
},
{
"school": {
"id": "109989",
"name": "University of Engineering & Technology"
},
"type": "College"
}
],
"id": "xxxxxxx"
}
Now i need the school names from this xml,
Try this..
You response is in Json format not xml.
JSONObject json = new JSONObject(response);
JSONArray education = json.getJSONArray("education");
for(int i = 0; i < education.length(); i++){
JSONObject con_json = education.getJSONObject(i);
String school_type = con_json.getString("type");
JSONObject school_json = con_json.getJSONObject("school");
String school_name = school_json.getString("name");
}
It is not XML. it is completely in Json Standard format.
first build a JSONobject from your data:
JSONObject jsonObj = new JSONObject(result); //result = your Data String in fetched from server
then you cab retrieve what you want using its key. for example:
jsonObj.getString("id"); // it returns "xxxxxxx". as is in your data

Categories

Resources