I tried parsing JSON data from "https://api.instagram.com/v1/media/popular?client_id="
+ clientId; or any other url, in a tons of different ways! Used couple of JSONParsers, tutorials, readers .. everything, but still can't to get anything from those urls. Now I am using Volley library and still can't get it to work, here is my code and everything you need, if anyone has any ideas , please share them.
public void LoadPictures() {
mRequestQueue = Volley.newRequestQueue(this);
mRequestQueue.add(new JsonObjectRequest(urlInst, null,
new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
parseJSON(response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}));
this is my parseJSON method:
private void parseJSON(JSONObject json) throws JSONException{
// JSONObject value = json.getJSONObject("value");
JSONArray items = json.getJSONArray("data");
for(int i=0;i<items.length();i++) {
JSONObject c=(JSONObject) items.get(i);
JSONObject user = c.getJSONObject("user");
String name= user.getString("username");
JSONObject img=c.getJSONObject("images");
JSONObject thum=img.getJSONObject("thumbnail");
String urlOfPic = thum.getString("url");
PhotoInst photoData=new PhotoInst (i, urlOfPic, name);
photos.add(photoData);
}
this is JSON data I was supposed to get :
"data": [{
"type": "image",
"users_in_photo": [],
"filter": "Gotham",
"tags": [],
"comments": { ... },
"caption": {
"created_time": "1296656006",
"text": "ãã¼ãâ¥ã¢ããªå§ãã¦ä½¿ã£ã¦ã¿ãã(^^)",
"from": {
"username": "cocomiin",
"full_name": "",
"type": "user",
"id": "1127272"
},
"id": "26329105"
},
"likes": {
"count": 35,
"data": [{
"username": "mikeyk",
"full_name": "Kevin S",
"id": "4",
"profile_picture": "..."
}, {...subset of likers...}]
},
"link": "http://instagr.am/p/BV5v_/",
"user": {
"username": "cocomiin",
"full_name": "Cocomiin",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1127272_75sq_1296145633.jpg",
"id": "1127272"
},
"created_time": "1296655883",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22518783",
"location": null
},
when I try putting random Toasts to see where is the problem, I can see the onResponse in my method LoadPictures isn't called at all? Where am I failing ? am I just overseeing something small or something else?
#Mate - As visible from your json, you are getting a JsonArray i.e. "data". Hence, change your Listener to Listener<JSONArray> whihc ensures that it returns a JSONArray object. As a result your onResponse will now become,
#Override
public void onResponse(JSONArray response) {
try {
parseJSON(response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Let me know if this works.
A few things you should verify first:
Are you sure you have the following in your manifest?
<uses-permission android:name="android.permission.INTERNET" />
Instagram requires some sort of API Key / authentication. Are you sure you are providing this?
Is your ErrorListener printing a stack trace? If it is, can you provide it?
That is where I would start.
may this help you response = response.substring(5); makes to remove first 5 characters like data: and continue with JSONArray jsonArray = new JSONArray(response);
Related
hello I'm trying t get the distance from a JSON object
{
"destination_addresses": [
"Rabat, Morocco"
],
"origin_addresses": [
"Marrakesh, Morocco"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "324 km",
"value": 323624
},
"duration": {
"text": "3 hours 24 mins",
"value": 12233
},
"status": "OK"
}
]
}
],
"status": "OK"
}
I succeeded to get the elements object but I can't get the distance
org.json.JSONException: No value for distance
at org.json.JSONObject.get(JSONObject.java:389)
at com.application.zarbagaskazay.colivoiturage.testMApsActivity$1.onResponse(testMApsActivity.java:66)
at com.application.zarbagaskazay.colivoiturage.testMApsActivity$1.onResponse(testMApsActivity.java:56)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
here is the code
public void onResponse(JSONObject response) {
try {
JSONArray rows = response.getJSONArray("rows");
JSONObject elements=rows.getJSONObject(0);
// JSONObject cc= elements.getJSONObject("distance");
System.out.println(elements.get("distance"));
button.setText(elements.get("distance").toString());
} catch (JSONException e) {
e.printStackTrace();
}
In my suggestion:
You can replace
System.out.println(elements.get("distance"));
with
System.out.println(elements.getJSONArray("elements").getJSONObject(0).getJSONObj
ect("distance"));
Above sop will print/extract "distance" json value.
{"text":"324 km","value":323624}
Hope it works at your end too!
JSONObject jsonObject = new JSONObject("YOUR RESPONSE STRING");
JSONArray jsonArray = jsonObject.getJsonArray("rows");
JSONArray jsonArray_elements =jsonArray.getJsonObject(0).getJsonArray("elements");
JSONObject jsonObject_distance =
jsonArray_elements.get(0).getJsonObject("distance");
String text = jsonObject_distance.getString("text");
String value = jsonObject_distance.getString("value");
I am trying to parse this json data from web service to android using volley.
This is the json array to be parsed.
[
{
"id":"1",
"conf_room_name":"Tadoba"
},
{
"id":"2",
"conf_room_name":"Melghat"
},
{
"id":"3",
"conf_room_name":"Ranthambore"
},
{
"id":"4",
"conf_room_name":"Corbett"
},
{
"id":"5",
"conf_room_name":"Pench"
}
]
[
{
"id":"1",
"area":"Mafatlal"
},
{
"id":"2",
"area":"Andheri"
}
]
[
{
"id":"1",
"type":"Is Personal"
},
{
"id":"2",
"type":"Meeting"
}
]
I am using this code to get the value out of my json array object ot different arraylists.
RequestQueue requestQueue2= Volley.newRequestQueue(this);
// RequestQueue requestQueue3= Volley.newRequestQueue(this);
// Create json array request
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST,"http://170.241.241.198/test.php",new Response.Listener<JSONArray>(){
public void onResponse(JSONArray jsonArray){
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArray_conf.add(jsonObject.getString("conf_room_name"));
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Error", "Unable to parse json array");
}
});
requestQueue2.add(jsonArrayRequest);
Only 1st array is being filled properly not the other one. I get outofboundsindex exception whenever i try using values from my 2nd arraylist.
All this happens on a button click only i want this to happen when i load my page.
Any help will be appreciated.
Make JSON as Array as below:
[
[
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
[
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
[
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
]
Or Object (easier to reading and understanding):
{
"rooms": [
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
"areas": [
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
"types": [
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
}
PHP code maybe like below:
<?php
$sqlroom = mysql_query("SELECT * FROM `room_table`");
$room_rows = array();
while($r = mysql_fetch_assoc($sqlroom)) {
$room_rows[] = $r;
}
$sqlarea = mysql_query("SELECT * FROM `area_table`");
$area_rows = array();
while($r = mysql_fetch_assoc($sqlarea)) {
$area_rows[] = $r;
}
$sqltype = mysql_query("SELECT * FROM `type_table`");
$type_rows = array();
while($r = mysql_fetch_assoc($sqltype)) {
$type_rows[] = $r;
}
$result = array();
$result["rooms"] = $room_rows;
$result["areas"] = $area_rows;
$result["types"] = $type_rows;
echo json_encode($result);
?>
You seem to be trying to parse three different types of data: conference rooms, areas (which presumably contain conference rooms?) and some information about either one (although it's not clear which). It therefore doesn't make sense to try and store these in a single array as each element contains a different data structure compared to the other two.
If the type is a description of one of the other two objects then it should be compassed within that object, not treated as a separate one. A room doesn't necessarily have to sit within an area but it might also make sense to have it there.
You say you are "pulling all these values from a mysql server and then using php to encode the json data which gives me the structure of the json array" which implies you do not have direct access to the JSON structure, but you should still have access to the PHP structure. The JSON encoder will use the design of the PHP array / object to structure the JSON so, for this to work you need to create more-or-less matching PHP and Java objects at either end of the serialization process.
For instance:
$obj = (object) array
('id' => '1', 'area' => 'Mafatlal', 'rooms' => array
('id' => '1', 'conf_room_name' => 'Tadoba', 'type' => 'Is Personal'),
...
('id' => '2', 'area' => 'Andheri', 'rooms' => array...
);
and
public class Area {
private int id;
private String area;
private Room[] rooms;
}
public class Room {
private int id;
private String conf_room_name;
private String type;
}
Note that, in contrast to the usual Java camel-case naming convention, object variables will usually have to match the incoming JSON variable name (i.e.: conf_room_name instead of confRoomName).
You need to add values using for loop.
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.toString.contains("conf_room_name"))
stringArray_conf.add(jsonObject.getString("conf_room_name"));
else if(jsonObject.toString.contains("area"))
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}
How can I parse this piece of JSON code?
{
"direction": "ltr",
"id": "feed/http => //www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"continuation": "CLKM0OyU0rYC",
"self": [
{
" href": "https => //cloud.feedly.com/reader/3/stream/contents/feed%2Fhttp%3A%2F%2Fwww.theverge.com%2Frss%2Ffull.xml?n=20&unreadOnly=true"
}
],
"alternate": [
{
"href": "http://www.theverge.com/",
"type": "text/html"
}
],
"updated": 1367539068016,
"items": [
{
"id": "entryId",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "NBC's reviled sci-fi drama 'Heroes' may get a second lease on life as Xbox Live exclusive",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "..."
},
"author": "Nathan Ingraham",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 15
},
{
"id": "entryId2",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "Senate rejects bipartisan gun control measure for background checks despite broad public support",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236136/senate-rejects-gun-control-amendment",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "...html content..."
},
"author": "T.C. Sottek",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 39
}
]
}
That is my solution but it doesn't work... what is my error? thanks
try{
//JSONArray elements = new JSONArray (response);
JSONObject json=new JSONObject(response);
JSONArray elements = json.getJSONArray("items");
Log.d(TAG, "Elemenenti numero" +elements.length());
// Getting Array of Contacts
// looping through All Contacts
for(int i = 0; i < elements.length(); i++){
JSONObject c = elements.getJSONObject(i);
// Storing each json item in variable
String identifier = c.getString("id");
String title = c.getString("title");
String link = c.getString("originId");
String data = c.getString("published");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date=new Date();
try {
date = format.parse(data);
System.out.println(date);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
String summary = summaryObj.getString("content");
JSONObject contentObj= c.getJSONObject("content");
String content = contentObj.getString("content");
JSONObject sourceObj= c.getJSONObject("origin");
String source = contentObj.getString("title");
if (summary.length()==0 && content.length()!=0) summary=content;
if (content.length()==0 && summary.length()!=0) content=summary;
String image=this.getFirstImage(content);
FeedItem toAdd=new FeedItem(identifier, title, link, date, null, summary, content, image, source);
toAdd.toString();
}
}catch (JSONException e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
There is no element called summary, you may try
if(c.has("summary")) {
JSONObject summaryObj= c.getJSONObject("summary");
}
if that doesn't work, please post your stacktrace, (logcat)
You don't have any tag named "originID". but you are trying to get String from it.
Similarly,you don't have tag "summary" also but you are trying to get JSONObject from it.
I'm working on Facebook Scores API for an android app. I query for the user score by accessing the user graph:
https://graph.facebook.com/user_id/scores&access_token={user_access_token}
I get a response like:
{
"data": [
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1200,
"application": {
"name": "QuizzlePeople",
"namespace": "quizzlepeople",
"id": "176694722487191"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1,
"application": {
"name": "Friend Smash!",
"namespace": "friendsmashsample",
"id": "480369938658210"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "Wordox",
"namespace": "wordox-the-game",
"id": "227993680602156"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "SongPop",
"namespace": "songpop",
"id": "323595464361460"
}
}
]
}
How do I extract useful data from this?
I'm trying to take something as a JSONObject, using:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/me?fields=score&access_token=" + token);
HttpResponse resp = client.execute(get);
Log.i("info1", resp.toString());
// Parse the response
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
Log.i("info1", response);
JSONObject result = new JSONObject(response);
JSONArray arr = result.getJSONArray("data");
Log.i("info2", arr.toString());
just to see if I can take anything, say, the array named 'data'. Yet the logcat does not show me anything. It shows the first 2 logs, but not the 3rd. Any ideas?
That looks like JSONObject. You can loop thru it and do whatever you wish with the data.
Have a look at http://json.org/ for documentation for a specific language (I presume you need java so click on the java link).
I appended the data to a table to give you an idea ( jquery / javascript ):
fiddle:http://jsfiddle.net/H8LNB/4/
I have the following json ,i am facing issue with creating jsonobject for this.Please let me know how to create a jsonobject with nested levels.
{
"menuConf": {
"class": "menu horizontal dropdown",
"caption": "",
"id": "mainMenu",
"container": "div",
"contClass": "navigation main left",
"helper": "span",
"items": [
{
"caption": "a",
"class": "orangesec",
"link": "#",
"id": "subMenu_1",
"helper": "span",
"items": [
{
"caption": "b",
"link": "#b"
},
{
"caption": "b",
"link": "#b"
},
{
"caption": "Blbogs",
"link": "#b"
},
{
"caption": "b",
"link": "#b"
}
]
}
]
}
}
What's wrong with the JSONObject(String) constructor? Just store your JSON text in a string and use it - it should handle nested objects just fine:
String json = "{...}";
try {
JSONObject o = new JSONObject(json);
// Print out the JSON text with a 4-space indentation
System.out.println(o.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}