Reputation: 37
I am trying to parse a simple JSON using Objective-C. My JSON file looks like the following:
{ "videosource": "hello my value" }
And my iOS Objective-C code:
NSError *error;
NSString *url_string = [NSString stringWithFormat: @"http://www.mywebsite.com/test"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"my -> json: %@", json);
//NSString *str = json[0]; //<- this one doest not work it makes app crush
//__NSSingleEntryDictionaryI objectAtIndexedSubscript:]: unrecognized selector sent to instance
//NSUInteger num = 0;
//NSString *str = [json objectAtIndex:num]; <- this one doest not work it makes app crush
I am trying to get the value from videosource key of JSON. How to do it?
Upvotes: 0
Views: 71
Reputation: 318774
Your JSON is a dictionary, not an array. { }
means dictionary. [ ]
means array. Pretty straightforward.
NSError *error = nil;
NSString *url_string = @"http://www.mywebsite.com/test";
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (json) {
NSString *source = json[@"videosource"];
} else {
NSLog(@"Error parsing JSON: %@", error);
}
Also, you really should not be using NSData dataWithContentsOfURL:
. Use NSURLSession
to get data from a remote URL.
Upvotes: 2