user1861458
user1861458

Reputation:

Can't get value in a NSDictionary

NSURL *jsonURL = [NSURL URLWithString:stringURL];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSString *stringImageURL = [jsonArray valueForKey:@"artworkUrl100"];

The last line is the issue. I can get the array perfectly fine but the value of stringImageURL is nil. How do I correctly retrieve the key highlighted below?

The NSDictionary value I want to use

Upvotes: 2

Views: 2114

Answers (2)

WDUK
WDUK

Reputation: 19030

NSString *stringImageURL = [jsonArray valueForKey:@"artworkUrl100"];

Should be

NSString *stringImageURL = [[[jsonArray valueForKey:@"result"]
                                      objectAtIndex:0]
                                        valueForKey:@"artworkUrl100"];

Or, more concisely

NSString *stringImageURL = jsonArray[@"result"][0][@"artworkUrl100"]; 

Why?

The data was nested 2 levels deeper than you thought, the dictionary value you were after was contained within an array, in another dictionary, under the key result.

Upvotes: 3

Joel
Joel

Reputation: 16124

First off, your jsonArray is not an array, but a dictionary.

Second, looks like you have a dictionary with an array of dictionaries, so it would be:

NSArray *resultsArray = [jsonArray valueForKey:@"results"];
NSDictionary *resultDict = [resultsArray objectAtIndex:0];
NSString *stringImageURL = [resultDict valueForKey:@"artworkUrl100"];

Upvotes: 1

Related Questions