Strictly Programming

JSON in Objective C 2.0 – simple sample 1

Posted in Uncategorized by sqllyw on 08/27/2013

Here is a very simple example accessing json file in Obj – c..

sample json file:



source code

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])

    @autoreleasepool {
        NSString *filename = @"/Users/username/sample1.json";
        NSError *fileError;
        NSDictionary *json;
        NSString *jdata = [[NSString alloc] initWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:&fileError];
        NSError *err;
        json = [NSJSONSerialization JSONObjectWithData:[jdata dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
        if (!json)
            NSLog(@"Error parsing : %@", err);
        // since we know the key name, we can access it directly
        NSString *user = [json objectForKey:@"user"];
        NSString *password = [json objectForKey:@"password"];
        NSLog(@"user is %@, password is %@", user, password);
        // we can access all keys
        NSLog(@"%@", [json allKeys]);
        // we can access all values
        NSLog(@"%@", [json allValues]);
    return 0;

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: