-4

I am trying to parse the following JSON response: http://www.breakingnews.com/api/v5/items?compact=false.

Here is my code to parse it:

NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.breakingnews.com/api/v5/items?compact=false"] options:NSDataReadingUncached error:&error];
if (error) {
    NSLog(@"%@", [error localizedDescription]);
} else {

    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error: &e];

    if (!jsonArray) {
        NSLog(@"Error parsing JSON: %@", e);
    } else {
        for(NSArray* item in jsonArray) {

            NSLog(@"Item: %@", item);

        }
    }

}

However, I'm getting this error:

-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x101810a40

Why is this - what am I doing wrong?

jszumski
  • 7,430
  • 11
  • 40
  • 53
James Anderson
  • 556
  • 3
  • 16
  • 41
  • That guy made the **exact same mistake.** And several others did so. You should search before asking. –  Apr 20 '13 at 20:29
  • @H2CO3, I still don't see where I'm going wrong? – James Anderson Apr 20 '13 at 20:32
  • The only strange thing is the alleged error message - I don't see a NSString in that code. Actually this code does not crash, it just displays the keys of the dictionary. Did you show all relevant code? – Martin R Apr 20 '13 at 20:33
  • I showed all the code I have, yup – James Anderson Apr 20 '13 at 20:36
  • 2
    I actually checked that code and it does not crash, it just does not show the expected result because (spoiler!) your JSON response is a dictionary and not an array. – Martin R Apr 20 '13 at 20:38
  • “Array” doesn't mean the same thing in Cocoa and in C as it does in some other languages: an array is a strictly serial collection of items, accessed by index (position in the series). An “associative array”, as some languages call it, is, in Cocoa, called a dictionary. `[…]` is an array; `{…}` is a dictionary. – Peter Hosey Apr 20 '13 at 22:57

1 Answers1

2

Check the types of the objects you're using. You're assuming that everything is an NSArray, when in fact things in JSON can be NSArray, NSDictionary, NSString, NSNumber, and NSNull.

drewmm
  • 737
  • 6
  • 17