I am trying to parse a result (JSON) fetched from the Facebook API using FQL in an Android Application.
I have been able to parse all of the result set except this part:
[10151392619250579,10151392618640579,10151392618590579,10151392618785579,10151392618835579,10151392618885579,10151392619010579,10151392619155579]
The FQL query I am making is:
SELECT app_data FROM stream WHERE filter_key in (SELECT filter_key FROM stream_filter WHERE uid = me() AND type = 'newsfeed') AND is_hidden = 0 LIMIT 200
Which returns a result like this:
{
"app_data": {
"attachment_data": "[]",
"images": "[10151392619250579,10151392618640579,10151392618590579,10151392618785579,10151392618835579,10151392618885579,10151392619010579,10151392619155579]",
"photo_ids": [
"10151392619250579",
"10151392618640579",
"10151392618590579",
"10151392618785579",
"10151392618835579",
"10151392618885579",
"10151392619010579",
"10151392619155579"
]
}
}
And this is the code I have used to fetch the data:
// GET THE APP DATA
if (JOFeeds.has("app_data")) {
String strAppData = JOFeeds.getString("app_data");
if (strAppData.equals("[]")) {
// DO NOTHING
} else {
JSONObject JOAppData = new JSONObject(strAppData);
if (JOAppData.has("photo_ids")) {
String strPhotoIDS = JOAppData.getString("photo_ids");
JSONArray JAPhotoIDS = new JSONArray(strPhotoIDS);
Log.e("JAPhotoIDS", JAPhotoIDS.toString());
for (int j = 0; j < JAPhotoIDS.length(); j++) {
JSONObject JOPhotoIDS = JAPhotoIDS.getJSONObject(j);
Log.e("PHOTO IDS", JOPhotoIDS.toString());
}
}
}
}
The logcat however, always shows this error:
12-13 15:54:36.390: W/System.err(5841): org.json.JSONException: Value 10151392619250579 at 0 of type java.lang.Long cannot be converted to JSONObject
Clearly I am wrong in the coding. Can anyone provide any suggestions on what the proper approach / code should be?
the part where you are parsing the photo_ids is wrong, it should be like:
if (JOAppData.has("photo_ids")) {
JSONArray JAPhotoIDS = JOAppData.getJSONArray("photo_ids");
Log.e("JAPhotoIDS", JAPhotoIDS.toString());
for (int j = 0; j < JAPhotoIDS.length(); j++) {
String id = JAPhotoIDS.getString(j);
Log.e("PHOTO IDS", id);
}
}
Your JSONArray JAPhotoIDS includes an array of Long (not JSONObject).
So instead using
JSONObject JOPhotoIDS = JAPhotoIDS.getJSONObject(j);
use
Long lPhotoIDS = JAPhotoIDS.getLong(j);
Related
I am fetching data from JSON to android.But, I am getting an empty JSON response. The PHP code which generates JSON data is as follows:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist[] = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
This is the JSON response.
{"dblist":[{"name":"a"},{"name":"arsod"}]}
The Java code to fetch data in android is as follows:
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
where institutes is an ArrayList in which I want to add each fetched element. But while fetching the data, I get the error in logcat org.json.JSONException: End of input at character 0 of. What is going wrong?
Considering the following:
s = {"dblist":[{"name":"a"},{"name":"arsod"}]}
Your code should be like,
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
remove this line:
JSONObject object = obj.getJSONObject("dblist");
and replace all occurences of object. with obj.
your JSONObject obj doesn't contain "dblist" object, there is only array inside it, so you should look for getJSONArray("dblist") straight inside obj
edit: you are parsing different String s, I've just checked this code:
final String s = "{\"dblist\":[{\"name\":\"a\"},{\"name\":\"arsod\"}]}";
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for (int i = 0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
which is almost exacly same as your and works pretty fine...
I'm trying to parse a JSON which contains:
"images": [
"https://d1wgio6yfhqlw1.cloudfront.net/sysimages/product/resized6/Interior_St_Pauls_Cathedral_132_12992.jpg",
"https://d1kioxk2jrdjp.cloudfront.net/resized/486x324/48-st_pauls_ctahedral_millenirm_bridge.jpg",
"http://i4.mirror.co.uk/incoming/article8299330.ece/ALTERNATES/s615b/LOND-2016-052-HMQ-St-Pauls-Thanks-Giving-704JPG.jpg"
]
The problem is that I don't know how to get the string of elements inside the "images" node
My code currently looks like:
if(c.has("images") && !c.isNull("images")){
JSONArray imagenes = jsonObj.getJSONArray("images");
for (int j = 0; j < imagenes.length(); j++) {
JSONObject m = imagenes.getJSONObject(i);
}
}
How can I get each string in the array without using a "key"?
I don't know what to do with "M" next.
You want a string, not an object. Strings don't have nested keys.
Use getString(i) method instead of getJSONObject(i)
Your images array contains with string values not with json object. So you need to get string instead of jsonObject.
if(c.has("images") && !c.isNull("images")){
JSONArray imagenes = jsonObj.getJSONArray("images");
for (int j = 0; j < imagenes.length(); j++) {
String imgURL = imagenes.optString(i);
System.out.println(imgURL);
}
}
Output:
https://d1wgio6yfhqlw1.cloudfront.net/sysimages/product/resized6/Interior_St_Pauls_Cathedral_132_12992.jpg
https://d1kioxk2jrdjp.cloudfront.net/resized/486x324/48-st_pauls_ctahedral_millenirm_bridge.jpg
http://i4.mirror.co.uk/incoming/article8299330.ece/ALTERNATES/s615b/LOND-2016-052-HMQ-St-Pauls-Thanks-Giving-704JPG.jpg
I am working in Android just for a heads up. I was able to retrieve JSON data but now I have come to the point where there are multiples. Example:
"workers":[
{
"id":3357,
"username":"Unreliable.worker",
"password":"x",
"monitor":0,
"count_all":41,
"count_all_archive":0,
"hashrate":477,
"difficulty":106.56
},
{
"id":4061,
"username":"Unreliable.worker2",
"password":"x",
"monitor":0,
"count_all":0,
"count_all_archive":null,
"hashrate":0,
"difficulty":0
}
would I have to do a for loop or is there another way to do it?
This is the code that I am using now to get them:
JSONObject workersJSONObject = personalJSONObject.getJSONObject("workers");
but I don't know how I would get for each and separate them. I'll get them by using:
id= workersJSONObject.getDouble("id");
[] in JSON refers to a JSON array. You could use something like:
JSONArray workersJSONArray = personalJSONObject.getJSONArray("workers");
Then loop through each item as (basically get each object inside array):
for (int i = 0; i < workersJSONArray.length(); i++) {
JSONObject workersJSONObject = workersJSONArray.getJSONObject(i);
// parse object just like before
}
On JSON, {} defines an object, [] defines an array instead. if you want details. see this and JSONArray
sample:
JSONArray workersJSOnArray = new JSONArray(stringData);
or
JSONArray workersJSOnArray = personalJSONObject.getJSONArray("workers");
/* THen you can loop from each data you want */
int len = workersJSOnArray.length();
for (int i = 0; i < len; i++)
{
JSONObject item = workersJSOnArray.optJSONObject(i);
int id = item.getInt ("id");
.....
}
I have following data from JSON
{
"MenuName": "starter dish",
"SubMenu": [
"pizza dish1",
"pizza dish2"
],
"Price": [
"100",
"110"
]
},
From here i can easily fetch data from "Menuname" key as starter dish but when I fetch data from "Submenu" I get whole string as ["pizza dish1", "pizza dish2"].
Please suggest me way to differentiate both pizza dish1 and pizza dish2
Submenu and Price is not String it is JSONArray so you will need to use for-loop to get all values from Submenu JSONArray as:
JSONArray jsonsubmenu=yourjsonobject.getJSONArray("Submenu");
for(int i=0;i < jsonsubmenu.length();i++){
// get all values from jsonsubmenu JSONArray..
String str_value=jsonsubmenu.optString(i);
....
}
try this
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getInt("SubMenu");
}
you can use this link for creating POGO class for your response. It will automatically generate class for your response.
Use google GSON library to parse your response.
or you can simply create a JSON Array or Objects to parse it. in your case it is JSON Object or JSON arrays.
Hi There in that senarerio you have to use
JSONArray _submenu = object.getJSONArray("SubMenu");
for (int i = 0; i < _submenu.length(); i++) {
String text = _submenu.getString(i);
}
JSONArray _price = object.getJSONArray("Price");
for (int i = 0; i < _price.length(); i++) {
String text = _price.getString(i);
}
You can retrieve array values and store it in string[] and use them as per your need. i.e., as follows..
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jSubmenu = jObject.getJSONArray("SubMenu");
subMenu = new String[jSubmenu.length()];
for (int i = 0; i < subMenu.length; i++) {
subMenu[i] = jSubmenu.getString(i);
}
JSONArray jPrice = jObject.getJSONArray("Price");
price = new String[jPrice.length()];
for (int i = 0; i < price.length; i++) {
price[i] = jPrice.getString(i);
}
} catch (Exception e) {
// TODO: handle exception
}
Just to throw in a quickie - read up on, and use GSON.
For simple small jobs I find it is the best. Not the fastest running for complex, or long structures, but really quick on the dev side.
Here's the link: google-gson
In my app, i want to parse json response which is in the format
{"quote":[{"orderId":"3209926"},{"totalpages":1}]}
below is the code which i had done,But the problem is how to get the "totalpages" value?
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
{
JSONObject offerObject = jArray.getJSONObject(i);
current.orderId = offerObject.getInt("orderId");
It shows error when i use
current.totalpage= offerObject.getInt("totalpages");
Anybody knows how to parse this?THanks in advance
Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.
For example, inside the for loop you can do the following:
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
current.totalpage= offerObject.getInt("totalpages");
}
You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.
I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.
for (int i = 0; i < jArray.length(); i++) {
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId")) {
current.orderId = offerObject.getInt("orderId");
} else if(offerObject.has("totalpages")) {
current.totalpage= offerObject.getInt("totalpages");
}
}