Objective C, NSDictionary loop through each object - objective-c

I am new to Facebook Developer. I want to create Mac OSX application using Facebook API. When i request FQL and its return me JSON data only like below:
My Code:
[self.result_text setString:[NSString stringWithFormat:#"%#",[result objectForKey: #"result"]];
It display:
[{"name":"My Name","first_name":"My First Name","last_name":"My Last Name"}]
I want to read the object inside this Dictionary. Example I just want to display "My Name" string. But I don't know how to it.
Thanks,

As Ashley Mills wrote, you should check the documentation. You can loop through the all dictionary keys like this:
for ( NSString *key in [dictionary allKeys]) {
//do what you want to do with items
NSLog(#"%#", [dictionary objectForKey:key]);
}
Hope it helps

You can parse the JSON contents from the server into a NSDictionary object via Lion's brand new NSJSONSerialization class (documentation linked for you).
e.g.
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData: [self.result_text dataUsingEncoding: NSUTF8StringEncoding] options: nil error: &error];
And once you have it in a NSDictionary object, it's easy to do something like:
NSString * myLastNameContent = [jsonDictionary objectForKey: #"last_name"];
Sergio's answer (which he keeps editing, even as I type :-) is very good too. +1 to him.

You can use JSONKit to transform the JSON string into a dictionary:
NSDictionary *resultsDictionary = [resultString
objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode|JKParseOptionValidFlags error:&err];
NSString* name = [resultDictionary objectForKey:#"name"];
JSONKit is straightforward to use and will make your application work also on older SDK versions.

You should read the documentation for NSDictionary here:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsdictionary_Class/Reference/Reference.html
in particular the section titled Accessing Keys and Values

Related

Objective C - how to Json Parse a dictionary having many dictionaries inside it?

Here is the main dictionary - 'query'.
I want to access 'results'- It is a NSDictionary having some key - pair values.
But, all the elements of 'query' dictionary (i.e count, results, created, lang, diagnostics) are inside 'query' dictionary's 0th element.
This is what I have written to access 'results'.
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"restuarant" ofType:#"json"]];
//query is main NSDictionary
self.query = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//results is an NSDictionary
self.results = [_query valueForKey:#"results"][0];
But, when I debug it, everything is getting saved in 'query' variable but nothing is getting stored in 'results' variable.
I also tried the following code, but that didn't work out as well -
self.results = [_query valueForKey:#"results"];
I have looked upon many other stackoverflow pages, but none of them suit my needs. Regards.
From what I understand, it should be something like:
//results is an NSDictionary
self.results = [[_query valueForKey:#"query"] valueForKey:#"results"];
To debug it easier and to understand better the structure, you can also break the access to the results dictionary, into multiple steps, like:
NSDictionary *queryDictionary = [_query valueForKey:#"query"];
self.results = [queryDictionary valueForKey:#"results"];
then you can check what you have in the first dictionary and then in the second one.
Hope this helps!

How do I get this value from NSMutableArray?

this is a fairly simple question.
I am using a web service in my app, and the server returns a JSON string to communitcate with the app.
Here is an example response:
{
repsonse = {
message = "Message";
"response_id" = X;
};
}
Using objective-c I want to be able to get what "response_id" is but I am unsure on how to do this.
Here is my code:
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
// Get json value
NSLog(#"%#", json);
if([json[#"response"][#"response_id"] isEqualToString:#"1"]){
return YES;
}else{
return NO;
}
Each time the isStringEqualTo method returns false.
Could somebody help me?
Thanks,
Peter
You have two problems:
json needs to be declared as an NSDictionary, not NSMutableArray since the JSON root is a dictionary, not an array. And you get back an immutable dictionary, not a mutable one.
The JSON has a key of "repsonse", not "response".

Understanding Json and NSData

We have to create a Jason file to send to server .
The way i found to do that is this :
NSDictionary* dic = #{#"Username" :userName,
#"Firstname" :firstName,
#"Lastname" : lastName,
#"Email" : email,
#"Password" : pass,
};
NSData* json = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
I dont really understand why after creating the dic , which is already a Json file, I have to use the NSJSONSerialization when creating the NSData ? ,why not just set the dic to the NSData ? What exactly this serialization do ?
Also ,why don't create just an NSString that will contain this structure ?
dic is an Objective-C dictionary (a collection of key-value pairs) and has nothing to do with JSON. Printing the dictionary might look similar to JSON, but it isn't.
NSJSONSerialization creates JSON data from the dictionary. JSON is a text format and is documented e.g. here: http://www.json.org. The JSON data for your dictionary would look like this:
{"Firstname":"John","Email":"jon#apple.com","Username":"john","Lastname":"Doe","Password":"topsecret"}
That NSJSONSerialization creates NSData and not NSString is just a design decision of the author of that class. You can convert the data to a string with
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];

How to check if NSURL contains NSString null?

I use the following code to get a NSString from a NSDictionary and then cast it into NSUrl:
NSURL * url = [NSURL URLWithString:[self.item objectForKey:#"website"]];
The NSDictionary self.item comes from a web server and it's correctly filled using JSON data. All the other objects inside the NSDictionary work perfectly fine.
But sometimes the web server passes a website url with the text "null" because the object has no website filled in. From debugging i learned that the NSURL object can contain a url with the text "null". But how do i prevent this, or how can i write an if statement that checks this?
I tried the following:
NSString * niks = [eventUrl absoluteString];
if(niks == #"null")
{
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Event" message:#"Event heeft geen website" delegate:nil cancelButtonTitle:#"Oke" otherButtonTitles:#"Oke", nil];
[message show];
}
else
{
[webView loadRequest:[NSURLRequest requestWithURL:eventUrl]];
NSLog(#"%#",eventUrl);
}
But this doesn't work, it always passes the url directly to the webview. Can someone set me in the right direction?
Your comparison;
if(niks == #"null")
only compares if the pointers are equal (i.e. if the two are the same string object instance). Since one is a constant and the other is created dynamically from JSON fetched from the server, it's very unlikely.
To compare the content of two strings, you should instead do;
if([niks isEqualToString:#"null"])
For the link thirsty, here is the [NSString isEqualToString:] documentation.
To do string comparison, you need to do [niks isEqualToString:#"null"], that's why the first condition is broken.
You can also use [niks RangeOfString:#"null"];
I believe you can do this:
id str = [self.item objectForKey:#"website"];
if([str isMemberOfClass[NSNull class]]) {
... its null
}
The JSON convertors all change null to a NSNull object (in my experience).
I am not 100% clear of my memory, but I encountered a situation where [NSDictionary objectForKey:] actually returned NSNull class instance instead of "null" string.
If this is the case, you can check the class of [self.item objectForKey:#"website"] by using isKindOfClass method.

parsing JSON using objective C?

I have spent 1 week studying objective C. Now I am quite confused at the dealing with data part.
My friend gave me a link
http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2
and ask me write a class to parse this JSON. I had no clue what parsing JSON means. but I have gone online and looked up. I could understand a basics of it and then I impletemented a punch of code to parse this JSON. Which is:
-
(void)parseURL
{
//create new SBJSON object
SBJSON *parser = [[SBJSON alloc] init];
NSError *error = nil;
//perform request from URL
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
NSDictionary *results = [parser objectWithString:json_string error:&error];
// array just for the "answer" results
NSArray *quizes = [results objectForKey:#"quiz"];
NSDictionary *firstQuiz = [quizes objectAtIndex:0];
// finally, the name key
NSString *extract = [firstQuiz objectForKey:#"extract"];
NSLog(#"this is: %#", [extract valueForKey:#"extract"]);
}
This is at the implementation file, but in the header file I could not declare any variables, it will print out some errors. I tried to run this, there is no errors, but I am not sure this code is correct or not. And my friend asked me to write a class into an existing project. I don't know what needs to be modified and what not. I am so blur right now. Could anyone pro in this give me a hand. ?
My sincere thanks.
Thanks for reply. I have downloading and added the JSON framework ealier too. I am just not sure where to begin and where to end, meaning the step I should do when I add JSON framework into it. I could understand the syntax but I am not sure about the steps I should do. I am a newbie in this.
If you support iOS 5.0+, you should use built-in NSJSONSerialization.
It is faster than TouchJSON.
You could just use TouchJSON: http://code.google.com/p/touchcode/wiki/TouchJSON
Or you could use this one: http://code.google.com/p/json-framework/
I'm sure there are others. I use TouchJSON... it's fast and has a good API.
I recommend working through Ray Wenderlich's MapKit tutorial, especially if you are a newbie. It covers several common iOS development issues, including parsing JSON data.
http://www.raywenderlich.com/2847/introduction-to-mapkit-on-ios-tutorial
"The Implementation" section is where his JSON feed is retrieved and then in "Plotting the Data" he uses the SBJson library to parse it.