Android Json Parsing from fql query result - android

I am developing a Facebook app for android.I am working with Facebook Stream table.
It gives me correct output. But I uable to parse return json string.
This is my Code :
void Query()
{
try
{
String fql = "SELECT attachment FROM stream WHERE post_id = '100008169074385_1408625132753109' ";
Bundle parameters = new Bundle();
parameters.putString("query", fql);
parameters.putString("method", "fql.query");
Session session = Session.getActiveSession();
// Log.v("esty", session.getAccessToken());
if (session != null && session.getState().isOpened()) {
Log.v("esty", session.getAccessToken());
Log.v("esty", session.getExpirationDate().toLocaleString());
}
parameters.putString("access_token", fb.getAccessToken());
String response = null; //hold my json String
response = fb.request(parameters); //Output JSON
Log.v("esty2", response);
}
catch(Exception ex)
{
Log.v("esty2", ex.getMessage());
}
}
output josn is:
{
"data": [
{
"attachment": {
"media": [
{
"href": "",
"alt": "",
"type": "swf",
"src": "https://fbexternal-a.akamaihd.net/app_full_proxy.php?app=87741124305&v=1&size=p&cksum=993c530ba81d9bc6b98190f1f4bbcb08&src=http%3A%2F%2Fi1.ytimg.com%2Fvi%2FOVOngbevN2o%2Fhqdefault.jpg",
"swf": {
"source_url": "http://www.youtube.com/v/OVOngbevN2o?list=PL6gx4Cwl9DGDiJSXfsJTASx9eMq_HlenQ&version=3&feature=share&autohide=1&autoplay=1&showinfo=1",
"preview_img": "https://fbexternal-a.akamaihd.net/app_full_proxy.php?app=87741124305&v=1&size=p&cksum=993c530ba81d9bc6b98190f1f4bbcb08&src=http%3A%2F%2Fi1.ytimg.com%2Fvi%2FOVOngbevN2o%2Fhqdefault.jpg",
"width": 0,
"height": 0,
"expanded_width": 0,
"expanded_height": 0
}
}
],
"name": "AJAX Tutorial - 19 - Creating Themes with CSS (+playlist)",
"href": "http://www.youtube.com/watch?v=OVOngbevN2o&feature=share&list=PL6gx4Cwl9DGDiJSXfsJTASx9eMq_HlenQ&index=18",
"caption": "Playlist by thenewboston",
"description": "Visit my website at http://thenewboston.com for all of my videos! \r\n\r\nMy Google+ - https://plus.google.com/108291790892450338168/posts\r\nFacebook - http://www.facebook.com/pages/TheNewBoston/464114846956315\r\nMy Twitter - http://twitter.com/#!/bucky_roberts\r\nMy Other YouTube Channel - http://www.youtube.com/thenewbostontv\r\nDonate - https://www.paypal.co...",
"properties": [
],
"icon": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t39.2081-0/10173489_10152389525269306_987289533_n.png"
}
}
]
}
I want source_url,preview_img from this json.
How can i parse this json. Please anyone help me..

Have a look at JSONObject and JSONArray
JSONObject json = new JSONObject(response);
That will be your whole JSON. Then you need to dig in to get the rest of it.
JSONArray data = json.getJSONArray("data");
JSONObject firstElement = data.getJSONObject(0);
JSONArray media = firstElement.getJSONObject("attachment").getJSONArray("media");
JSONObject anotherFirstElement = media.getJSONObject(0);
String source_url = anotherFirstElement.getJSONObject("sfw").getString("source_url");
To dig in and see what is going on, you can always do a System.out.println(json.toString(4)); to see what is going on in each element.

Related

Switching JSON response from custom to WP API V2

I have a question about converting from a custom JSON response to WordPress standard JSON response for WP V2 API.
My custom json response looks like this - it's framed within
{
"categories":
[26]
0:
{
"term_id": 12
"name": "Android"
"slug": "android"
"term_group": 0
"term_taxonomy_id": 12
"taxonomy": "category"
"description": ""
"parent": 463
"count": 10
"filter": "raw"
"cat_ID": 12
"category_count": 10
"category_description": ""
"cat_name": "Android"
"category_nicename": "android"
"category_parent": 463
}
}
My code looks like this
// Preparing volley's json object request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
List<Category> categories = new ArrayList<Category>();
try {
if (response.has("error")) {
String error = response.getString("error");
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
}else {
// Parsing the json response
JSONArray entry = response.getJSONArray(TAG_CATEGORIES);
// loop through categories and add them to
// list
for (int i = 0; i < entry.length(); i++) {
JSONObject catObj = (JSONObject) entry.get(i);
// album id
String catID = catObj.getString(TAG_TERM_ID);
// album title
String catTitle = catObj.getString(TAG_TERM_NAME);
Category category = new Category();
category.setId(catID);
category.setTitle(catTitle);
// add album to list
categories.add(category);
}
The WordPress RST API V2 the JSON response looks like this:
[10]
0: {
"id": 12
"count": 10
"description": ""
"link": "https://torbjornzetterlund.com/category/technology/mobile-apps/android/"
"name": "Android"
"slug": "android"
"taxonomy": "category"
"parent": 463
"img": false
"_links": {
"self": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/categories/12"
}-
- "collection": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/categories"
}-
- "about": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/taxonomies/category"
}-
- "up": [1]
0: {
"embeddable": true
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/categories/463"
}-
-"wp:post_type": [1]
0: {
"href": "https://torbjornzetterlund.com/wp-json/wp/v2/posts?categories=12"
}-
- "curies": [1]
0: {
"name": "wp"
"href": "https://api.w.org/{rel}"
"templated": true
}
}
}
}
The new JSO response do not have a category called categories, so I can not use this statement.
// Parsing the json response
JSONArray entry = response.getJSONArray(TAG_CATEGORIES);
I can not find any good documentation for the volley library or examples, my current code gets an object from the url, then the code uses the response.getJSONArray to get the array from the object.
What do I need to do if I can not identify the Array within the object, the json response I get is an array, should I change the request from object to array. I'm not sure a bit lost on this one. Appreciate any help.
You are using an JsonObjectRequest, what was right for your api but now it comes an JsonArray from your api.
There is also a JsonArrayRequest in the Volley Toolbox. If you change the Request Type then it will work.
If something is not clear, feel free to ask.
This is how my code snippet looks like after the change from JsonObjectRequest to JsonArrayRequest
JsonArrayRequest jsonArrReq = new JsonArrayRequest(url, new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
List<Category> categories = new ArrayList<Category>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject catObj = response.getJSONObject(i);
// album id
String catID = catObj.getString(TAG_TERM_ID);
// album title
String catTitle = catObj.getString(TAG_TERM_NAME);
Category category = new Category();
category.setId(catID);
category.setTitle(catTitle);
// add album to list
categories.add(category);
// Store categories in shared pref
AppController.getInstance().getPrefManger().storeCategories(categories);
// String the main activity
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {

How to check the status in json object to get the image from array of object in android

First I need to check the json object status 400 if status 400 to get the image otherwise it shows error. I don't how to check status in JSON empty object in android volley. and also I need some help on how to get image by using banner path and banner name.
My Json
{
"status": "200",
"requestType": "bannerImages",
"basePath": "http:\/\/192.168.0.33\/cartwebsite3\/",
"bannerPath": "http:\/\/192.168.0.33\/cartwebsite3\/cdn-images\/banner\/",
"response": {
"data": [
{
"banner_id": "37",
"banner_name": "1457324300894ac3df08bd3648452703d8412f82c2.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324300"
},
{
"banner_id": "36",
"banner_name": "14573242986be953c24858a3c2d787d57e6b77be1f.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324298"
},
{
"banner_id": "35",
"banner_name": "1457324295f8d8153fb4f29d3af15276db22435d48.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324295"
}
]
},
"request": {
"postData": [],
"getData": {
"type": "bannerImages",
"result": "json"
}
}
}
Thank in Advance
If you just want to get status, try like this:
JSONObject jsonObject = new JSONObject(jsonString);
String status = jsonObject.optString("status");
if you want to parse whole data, I would recommend you to use Gson.
For easy JSON parsing/manipulating/etc use GSON library at android. Example you can make custom objects and straight create new instance of your custom object from parsing and then just check fields or whatever you need to do.
CustomObject object= gson.fromJson(JSON, CustomObject.class);
if(object.bannerPath != null) {
//Do something
}
Here is the GSON in Github
and here for GSON tutorial
//editing Rohit Arya Code little bit
JSONObject jsonObject = new JSONObject(jsonString);
String status = jsonObject.optString("status");
if(status.equalIgnorecase("400")){
try {
JSONObject jsonObject=new JSONObject("yourResponse");
jsonObject1=jsonObject.getJSONObject("response");
JSONArray jsonArray=jsonObject1.getJSONArray("data");
JSONObject jsonObject2;
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
String banner_name=c.getString("banner_name");
Log.e("banner_name",banner_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
// don't download
}

android Json Api Key Value Nested how to use

Android Json Api Key Nested how to use ?MsgID ,UsrID Repeat how to call? Volley
I have a json which has a number of nested JSONARRAY.
{
"status": "success",
"data": {
"2547": {
"MsgID": "2547",
"UsrID": "352",
"MsgID": "221",
"ThroughUsrID": null,
"MsgID": "1",
"MsgDt": "2016-03-22 11:55:13",
"buscard": {
"UsrID": "221",
"EntID": "7",
"EntID": "1",
"UsrFavorites": 0,
"UsrLinkSts": "connected"
},
}
}
I think you are trying to parse Json data. Try to do something like this:
try {
JSONObject jsonObject = new JSONObject(stringToParse);
JSONObject data = jsonObject.optJSONObject("data");
JSONObject tempData = data.optJSONObject("2547");
String msgID = tempData.optString("MsgID");
// Similarly parse other info
JSONObject busCard = tempData.optJSONObject("buscard");
//Again parse required data from busCard
} catch (JSONException e) {
e.printStackTrace();
}

Android JSON org.json.JSONEXCEPTION: No Value for ""

I am trying to use Android get the SpeedLimit value from a JSON server response (HERE API - http://route.st.nlp.nokia.com/routing/6.2/getlinkinfo.json?waypoint=52.5308,13.3846&app_id=your_app_id&app_code=your_app_code):
{
"Response": {
"MetaInfo": {
"MapVersion": "2015Q1",
"ModuleVersion": "0.2",
"InterfaceVersion": "4.2",
"Timestamp": "2015-08-25T16:15:23.540Z"
},
"Link": [
{
"_type": "PrivateTransportLinkType",
"LinkId": "-931447246",
"Shape": [
"52.5309486,13.38447",
"52.5306702,13.38344",
"52.5305786,13.38307"
],
"SpeedLimit": 13.89,
"DynamicSpeedInfo": {
"TrafficSpeed": 8.89,
"TrafficTime": 11.6,
"BaseSpeed": 13.89,
"BaseTime": 7.4
},
"Address": {
"Label": "Invalidenstraße",
"Country": "DE",
"State": "Berlin",
"County": "Berlin",
"City": "Berlin",
"District": "Mitte",
"Street": "Invalidenstraße"
}
}
]
}
}
Here is the code I'm using the get the result out of the JSON:
try {
JSONObject response = new JSONObject(jsonResult);
JSONObject test = response.getJSONObject("Link");
String test1 = test.getString("SpeedLimit");
Toast.makeText(getApplicationContext(), test1,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
I keep getting the following exception:
org.json.JSONEXCEPTION: No Value for Link
I must be asking for the wrong information within the JSON but I can't seem to work this one out.
Thank you everyone!
Link JSONArray is inside Response JSONObject instead of in root JSONObject.
So, first need to get Response JSONObject from response then get Link JSONArray:
// Response JSONObject
JSONObject responseJSONObject = response.getJSONObject("Response");
// get Link JSONArray from responseJSONObject
JSONArray linkJSONArray = responseJSONObject.getJSONArray("Link");
The "Link" is a JSONArray instead of JSONObject.
So the code should be :
try {
JSONObject response = new JSONObject(jsonResult);
JSONArray test = response.optJSONArray("Link");
if (test != null && test.length() > 0) {
JSONObject test = test.optJSONObject(0);
if( test != null) {
String test1 = test.getString("SpeedLimit");
Toast.makeText(getApplicationContext(), test1, Toast.LENGTH_SHORT).show();
return;
}
}
Toast.makeText(getApplicationContext(), "No speed limitation data found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
You also need to consider the situation that there are more than 1 JSONObject included in the Link JSONArray.

Parsing JSON response in Android

I am writing a httpget request for android that queries the foursquare api for nearby event. The JSON responce I receive back is
{"groups": [
{
"type": "Nearby",
"venues": [
{
"id": 2587838,
"name": "Marriott Druids Glen Hotel Newtownmountkennedy",
"primarycategory": {
"id": 79281,
"fullpathname": "Travel:Resort",
"nodename": "Resort",
"iconurl": "http://foursquare.com/img/categories/travel/resort.png"
},
"address": "Newtownmountkennedy",
"city": "Newtownmountkennedy",
"state": "",
"verified": false,
"geolat": 53.091717,
"geolong": -6.079162,
"stats": {
"herenow": "0"
},
"distance": 5596
},
There can be many of these venues. I can get it to print out the venues information using this code
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
Log.i("Hoosheer0",result);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
JSONArray venues = json.getJSONArray("groups");
//JSONArray docsArray = jObject.getJSONArray("docs");
for (int i = 0; i<venues.length();i++){
String name = venues.getJSONObject(i).optString("venues");
//String venueName = name.
Log.i("This is a name... pleasse", name);
}
instream.close();
How can I access the geolat & geolong values?
I believe placing this code inside your for-loop should do the trick:
JSONObject venueObject = venues.getJSONObject(i);
double geoLat = venueObject.getDouble("geolat");
double geoLong = venueObject.getDouble("geolong");
You can check here and pick a JSON library to use to get at those values.

Categories

Resources