I'm making the following simple request to Facebook. My goal is to grab the names of all a user's photo albums:
[[AppDelegate sharedDelegate].facebook requestWithGraphPath:#"me/albums" andDelegate:[AppDelegate sharedDelegate]];
Then, I get a JSON response from the server like such:
data = (
{
"can_upload" = 1;
count = 4;
"cover_photo" = 321491374598618;
"created_time" = "2012-06-04T21:46:23+0000";
from = {
id = 100002132746588;
name = "Owner....";
};
id = 321491371265285;
link = "http://www.facebook.com/album.php?fbid=321491371265285&id=100002132746588&aid=73680";
name = "Photos";
privacy = custom;
type = normal;
"updated_time" = "2012-06-04T22:08:39+0000";
},
{
"can_upload" = 0;
count = 1;
"cover_photo" = 318401854907570;
"created_time" = "2012-05-31T00:00:35+0000";
description = "Which Friend Stalks You the Most?";
from = {
id = 100002132746588;
name = "Owner....";
};
id = 318401848240904;
link = "http://www.facebook.com/album.php?fbid=318401848240904&id=100002132746588&aid=73163";
name = "Which Friend Stalks You the Most?";
privacy = friends;
type = normal;
"updated_time" = "2012-05-31T00:00:36+0000";
},
And so on. Problem is, when I try to parse the data with:
NSLog(#"%#", [result objectForKey:#"name"]);
I get null. I assume this is happening because the NSDictionary that the data is returned in does not know which name entry to concentrate on. How do I parse the data so that I get the names of all the albums?
"result" is actually an array of dictionaries, so loop through the array and then grab name from each element in the array.
for (NSDictionary *anAlbum in [result objectForKey:#"data"]) {
NSLog(#"%#", [anAlbum objectForKey:#"name"]);
}
Related
I'm using an API to get weather condition and the retrieved dict is
dict = {
base = stations;
clouds = {
all = 92;
};
cod = 200;
coord = {
lat = "31.23";
lon = "121.47";
};
dt = 1476853699;
id = 1796231;
main = {
"grnd_level" = "1028.63";
humidity = 93;
pressure = "1028.63";
"sea_level" = "1029.5";
temp = "73.38";
"temp_max" = "73.38";
"temp_min" = "73.38";
};
name = "Shanghai Shi";
rain = {
3h = "0.665";
};
sys = {
country = CN;
message = "0.0125";
sunrise = 1476827992;
sunset = 1476868662;
};
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
wind = {
deg = "84.50239999999999";
speed = "5.97";
};
}
If I want the value of humidity, I just use
let humidityValue = dict["main"]["humidity"] and it works.
But the problem is I also want to get the value of description in weather
when I used let dscptValue = dict["weather"]["description"]
it retrieved nil.
How's that? and I notice there are two brackets around weather .I'm not sure whether it is the same with the statement without brackets.
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
How to get the value of description?
weather keys contains Array of Dictionary not directly Dictionary, so you need to access the first object of it.
if let weather = dict["weather"] as? [[String: AnyObject]], let weatherDict = weather.first {
let dscptValue = weatherDict["description"]
}
Note: I have used optional wrapping with if let for preventing crash with forced wrapping.
Weather is an array of dictionaries.
dict["weather"][0]["description"]
may give you the expected result.
I have an application which retrieves a JSON file. Here you are a piece of my code:
Array definition
var photos: NSArray = []
How I populate the array:
ezJson().createRequest("http://myapiurl/load", type: "GET", params: nil, completion: {(returnedObject : AnyObject?, error : NSError?)in
if returnedObject{
self.photos = returnedObject as NSArray
self.tableView.reloadData()
}
})
println(self.photos)
{
created = {
date = "2014-06-13 18:35:46";
timezone = "Europe/Madrid";
"timezone_type" = 3;
};
description = description1;
id = 3;
name = 539b286277617;
},
{
created = {
date = "2014-06-13 18:38:38";
timezone = "Europe/Madrid";
"timezone_type" = 3;
};
description = description2;
id = 4;
name = 539b290ed8577;
}
println(self.photos[0])
{
created = {
date = "2014-06-13 18:35:46";
timezone = "Europe/Madrid";
"timezone_type" = 3;
};
description = description1;
id = 3;
name = 539b286277617;
}
The problem is, I don't know how to get a particular item. I've tried:
println(self.photos[0]) // it works
println(self.photos[0]["name"] // Xcode crash "Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254"
println(self.photos[0].name) // returns nil
How can I access to the name parameter ?
It seems that you are casting a String to NSArray. This won't give you the effect that you want.
First of all, if you want to acces your elements by name, you want an NSDictionary.
Then it propably still won't work, as there is no implicit conversion between the types so you will have to either parse it yourself or use some JSON library.
Last : your JSON is incorrect.
I am getting the JSON response from youtube API v3 for https://www.googleapis.com/youtube/v3/channels?part=statistics&id
and receiving JSON response as
{
etag = "\"rFqCJSkEICLP3Hq6a4AADI7kf48/2zirKmd0WgUqY0RzlyD4hlACeWM\"";
items = (
{
etag = "\"rFqCJSkEICLP3Hq6a4AADI7kf48/u4TmQ5XfIQQg6y6u4Od2yULCVlc\"";
id = "HCcrj0EHvn_Y8";
kind = "youtube#channel";
statistics = {
commentCount = 0;
subscriberCount = 21694;
videoCount = 124582;
viewCount = 0;
};
},
{
etag = "\"rFqCJSkEICLP3Hq6a4AADI7kf48/2p4_mjrZLfhO6bDvH-RgAykNQr8\"";
id = UCX2v47KsDKqajrEYFV7GbBg;
kind = "youtube#channel";
statistics = {
commentCount = 6460;
subscriberCount = 494656;
videoCount = 33;
viewCount = 713607227;
};
}
}
when I am trying to display the
cell.viewsChannel.text=[[_statistics valueForKeyPath:#"statistics.videoCount"] objectAtIndex:indexPath.row];
the value doesn't display on table view.
I tried to format the output as unsigned long ,int but the correct values don't show.
Please help
Thanks in advance
I think you need to add item to valueForKeyPath
cell.viewsChannel.text=[[_statistics valueForKeyPath:#"item.statistics.videoCount"] objectAtIndex:indexPath.row];
I have an array called someArray. I would like to access the name value of the NSArray. I'm trying to access it using the following, but with out any luck. How do I do it properly?
cell.textLabel.text = [[someArray objectAtIndex:indexPath.row] objectForKey:#"name"];
some array {
haserror = 0;
headers = {
code = 0;
haserror = 0;
nodeid = "fe1.aaaaaa.2.undefined";
time = 16;
};
results = (
{
coords = (
"44.916667",
"8.616667"
);
id = 2;
key = alessandria;
name = Alessandria;
state = Piemonte;
zip = 1512;
},
{
coords = (
"43.616944",
"13.516667"
);
id = 3;
key = ancona;
name = Ancona;
state = Marche;
zip = 601;
},
}
As far as i see from you data model, the key name is a node under the key results. You can use this data model as a dictionary map, the code snippet below must give you what you need..
NSDictionary *myObject = [[someArray objectAtIndex:indexPath.row] objectForKey:#"results"];
cell.textLabel.text = [myObject objectForKey:"name"];
IMPORTANT NOTE: If you have some lopps or some other mechanisms for receiving data, there may be more efficent ways for your sıolution, so please give some more additional info about what you are exactly tryin to do
As others have noted, someArray is a dictionary while results is a key pointing to an array inside of your dictionary. If you want an array of all of the name fields in your results array, you could use valueForKeyPath: on the someArray variable, like this:
NSArray *names = [someArray valueForKeyPath:#"results.name"];
The names variable should now contain "Alessandria", and "Ancona" from the data set your show in your example code.
hi friend this is my JSON file apitest[18318:207] { ErrorCode = 900; ErrorMessage = ""; Result = ( { DeviceInfoId = 12; Email = "rocky#itg.com"; FirstName = Rocky; LastName = Yadav; ProfileImage = "<null>"; ThumbnailImage = "<null>"; UserId = 153; } ); TokenID = 59nUniliob; isError = 0; }
Can you please explain me how to parse the above JSON file and save the values in sqlite database this
You can use the SBJson parser to get a dictionary/array out of a json (depending on your response). You can then get the individual values from the dictionary/array and save them into your database.
The git repo also has some examples on how to use the parser.