0

I am trying to parse this json:

{
    "myData": [
        {
            "date": "2013-07-29",
            "preferredMeetingLocation": "home",
            "isbn": null,
            "category": "Clothing",
            "price": "5",
            "title": "clothingstuff",
            "description": "Desc"
        },
        {
            "date": "2013-07-29",
            "preferredMeetingLocation": "home2",
            "isbn": null,
            "category": "Clothing",
            "price": "2",
            "title": "other",
            "description": "Desc2"
        }
    ]
}

So far I have:

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
    NSDictionary *results = [json objectForKey:@"myData"];
for (NSDictionary *item in results) {
    NSLog(@"results::%@", [results objectForKey:@"title"]);
}

but I get Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8877e40'

The main goal is to be able to parse the data received and then display each set of info in a cell.

What am I doing wrong?

1
  • You're doing precisely what the message says you're doing: Trying to perform "objectForKey" on an NSArray. Commented Jul 29, 2013 at 18:30

2 Answers 2

2

The line

 NSLog(@"results::%@", [results objectForKey:@"title"]);
 //                        ^---- Wrong variable used here!

should be

 NSLog(@"results::%@", [item objectForKey:@"title"]);
Sign up to request clarification or add additional context in comments.

2 Comments

ah shoot thanks, also if I want to get the count for how much items came back, in this case 2, how do I get that? I think its something like [[results allKeys] count]; but that crashes as well
@BluGeni: Note that results should be an array: NSArray *results = ... as @rmaddy correctly said in his answer. And then [results count] should work.
1

results should be an array. And you are logging the wrong object.

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
NSArray *results = [json objectForKey:@"myData"];
for (NSDictionary *item in results) {
    NSLog(@"title::%@", [item objectForKey:@"title"]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.