How to get a Dictionary Object from a Web Service - ios

I'm using a web service that gives back JSON data of jobs. I have called the service and displayed ALL the JSON data as such:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = #"http://jobs.github.com/positions.json?description=python&location=new+york";
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSString *item = [json objectAtIndex:0];
NSLog(#"%#", item);
// Do any additional setup after loading the view.
}
So this returns one job with TON of information such as "description", "company name", "location". I want to be able to get JUST location or JUST description. How would I go about doing that?
All help is appreciated, thanks.

you get an array of dictionaries... replace
NSString *item = [json objectAtIndex:0]; //old
with
for(NSDictionary *item in jsonArray) {
NSLog(#"Item desc : %#", item[#"description"]);
}

In your case you can access it directly:
NSDictionary *item = [json objectAtIndex:0];
NSString *location = [item objectForKey:#"location"];
NSLog(#"%#", location);

Reading the following article will give you a good grounding on parsing JSON data.
http://www.intertech.com/Blog/basic-json-parsing-in-ios/

Related

How to retrieve data from local file of json to a dictionary in Objective C iOS

I have trouble in retrieving the data from my JSON file to a dictionary and then I will access the values inside array of that dictionary to take the time and compare the time what I have done so far is that.
Note: I have multiple timings for one month.
in my viewDidLoad I have defined
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:#"/Users/macbook/Desktop/Test/Test/myFile.json"];
NSString *fileContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"Json data is here %#", fileContent);
saving data in dictionary
NSArray *data = [[theFeedString JSONValue] objectForKey:#"data"];
for (NSDictionray *dict in data) {
NSString *timings = [[dict objectForKey:#"timings"] intValue];
}
in my console I get all the data from my json and my json look like this
{
"data": [
{
"timings": {
"Sunrise": "07:14 (PKT)",
"Sunset": "18:15 (PKT)",
"Midnight": "00:45 (PKT)"
}
},
{
"timings": {
"Sunrise": "07:13 (PKT)",
"Sunset": "06:40 (PKT)",
"Midnight": "00:45 (PKT)"
}
}
]
}
You should do like this way, where Palettes.json is a local file.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Palettes" ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
Let me know if there is any query.
UPDATE
According to your Output of JSON, you will get data array like this,
NSArray *data = json["data"];
[data enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
NSDictionary *timings = object["timings"];
NSString *sunrise = timings["Sunrise"];
}];
You can iterate through data array to get timings

Store JSON output in NSArray

Good morning,
I'm trying to develop my first App and I'm using TableView in order to show my entries from a MySQL database and I'm having some trouble when I have to parse the JSON output.
I have already created the connection with my JSON, but now I need to save all the id in a single Array, all the user in another array, etc, etc. As you can see below in my second code, I need to store them in a NSArray. How can I do that?
That's my JSON
[{"id":"15","user":"1","imagen":"http:\/\/farmaventas.es\/images\/farmaventaslogo.png","date":"2014-09-13"}
,{"id":"16","user":"2","imagen":"http:\/\/revistavpc.es\/images\/vpclogo.png","date":"2014-11-11"}]
And that's my TableViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here I have to store my "user"
self.carMakes = [[NSArray alloc] initWithObjects: nil];
// Here I have to store my "imagen"
self.carModels = [[NSArray alloc] initWithObjects: nil];
}
Thanks in advance.
That's another solution with KVC
NSArray *carMakes = [json valueForKeyPath:#"#unionOfObjects.id"];
NSArray *carModels = [json valueForKeyPath:#"#unionOfObjects.user"];
First of all, you would want to fetch JSON on another thread, so you dont block your main thread with it:
#interface ViewController ()
#end
#implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
self.carModels = [[NSMutableArray alloc] init];
#try {
NSError *error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:theData
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error){
NSLog(#"%#",[error localizedDescription]);
}
else{
for(int i=0;i<json.count;i++){
NSDictionary * jsonObject = [json objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[carModel addObject:imagen];
}
dispatch_async(dispatch_get_main_queue(), ^{
// If you want to do anything after you're done loading json, do it here
}
});
}
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here you have to store my "user"
self.userArray = [[NSMutableArray alloc]init];
for (NSDictionary *userInfo in json){
//get "user" from json
NSString* user = [userInfo objectForKey:#"user"];
//add to array
[userArray addObject:user];
}
You have use NSMutableArray to add object instead.
Since "json" is array of NSDictionary you can get iterate over it and add to arrays like this:
NSArray *json = #[#{#"id":#"15",#"user":#"1",#"imagen":#"http:\/\/farmaventas.es\/images\/farmaventaslogo.png",#"date":#"2014-09-13"},
#{#"id":#"16",#"user":#"2",#"imagen":#"http:\/\/revistavpc.es\/images\/vpclogo.png",#"date":#"2014-11-11"}];
NSArray *carMakes = [NSArray array];
NSArray *carModels = [NSArray array];
for (NSDictionary *dict in json) {
carMakes = [carMakes arrayByAddingObject:dict[#"id"]];
carModels = [carModels arrayByAddingObject:dict[#"user"]];
}
NSLog(#"%#",carMakes);
NSLog(#"%#",carModels);

How to get the values from json service [duplicate]

This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
 NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
 
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details

Using NSArray and NSDictionary to access a JSON object without a root element

Here's an example of my data:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
I'm trying to retrieve the value for last_price by loading the contents of my NSDictionary into an Array.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
self.darkPosts = [NSMutableArray array];
NSArray *darkPostArray = [darkDict objectForKey:#""];
for (NSDictionary *darkDict in darkPostArray) {...
But my json doesn't have a root element, so what do I do?
Additionally, when using the suggested answer, the output is ("...
- (void)viewDidLoad{
[super viewDidLoad];
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSString *lastP = [darkDict valueForKey:#"last_price"];
self.dark_label.text = [NSString stringWithFormat: #"%#", lastP];
}
It looks like you are wanting to iterate over your results. The root element is an array not a dictionary so you can just start iterating
NSError *error = nil;
NSArray *items = [NSJSONSerialization JSONObjectWithData:darkData
options:kNilOptions
error:&error];
if (!items) {
NSLog(#"JSONSerialization error %#", error.localizedDescription);
}
for (NSDictionary *item in items) {
NSLog(#"last_price => %#", item[#"last_price"]);
}
If you literally just want to collect an array of the last_price's then you can so this
NSArray *lastPrices = [items valueForKey:#"last_price"];
Convert the JSON to an NSArray with NSJSONSerialization. Then access the value:
NSData *darkData = [#"[{\"code\":\"DRK\",\"exchange\": \"BTC\",\"last_price\": \"0.01790000\",\"yesterday_price\": \"0.01625007\",\"top_bid\": \"0.01790000\"}, {\"top_ask\": \"0.01833999\"}]" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:darkData
options:0
error:&error];
NSString *value = array[0][#"last_price"];
NSLog(#"value: %#", value);
NSLog output:
value: 0.01790000
If you are having trouble post the code you have written to get some help.
-- updated for new OP code:
The web service returns a JSON array or dictionaries not a JSON dictionary. First you have to index into the array and then index into the dictionary.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSArray *darkArray = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
NSLog(#"lastP: %#", lastP);
NSLog output:
lastP: 0.01970000
Note that the two lines:
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
can be replaced with the single line using array indexing:
NSString *lastP = darkArray[0][#"last_price"];
Where the "[0]" gets the first array element which is a NSDictionary and the "[#"last_price"]" gets the names item from the dictionary.

How to get a GDATA for a Single Youtube video?

How can I get single video information using gdata from youtube.
I know I can get a playlist using this code:
However the code does not work to get a single video's data
NSURL *blogURL = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/playlists/PL85E8F3CC22BCEDC6?v=2&alt=jsonc"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *data1 = [dataDictionary objectForKey:#"data"];
NSDictionary *item = [data1 objectForKey:#"items"];
for (NSDictionary *video in item) {
NSDictionary *title = [video objectForKey:#"video"];
NSArray *titleArray = [title objectForKey:#"title"];
NSLog(#"%#",titleArray);
NSString*t = [title objectForKey:#"title"];
NSLog(#"Title:%#", t);
...
}
But I do not know how to get a single video.
Any help will be appreciated...
Thanks...
To get the feed for a single video with v2, you'd replace the URL in the first line with something like this:
https://gdata.youtube.com/feeds/api/videos/tge2BfiIXiE?v=2&alt=jsonc
Where you change the videoID as necessary.
The JSON that is returned with this feed is slightly different, naturally; so rather than creating an NSDictionary object for the items list and then looping over it, you would just do something like this:
NSURL *feedURL = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/videos/tge2BfiIXiE?v=2&alt=jsonc"];
NSData *jsonData = [NSData dataWithContentsOfURL:feedURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *data1 = [dataDictionary objectForKey:#"data"];
NSString *t = [data1 objectForKey:#"title"];
NSLog(#"Title:%#", t);
NSDictionary *thumbs = [data1 objectForKey:#"thumbnail"];
NSURL *standardThumb = [thumbs objectForKey:#"sqDefault"];
NSURL *hdThumb = [thumbs objectForKey:#"hqDefault"];
code edited to reflect question in comment

Resources