-1

I have a problem parsing JSON string in Objective C: My JSON:

{"messages":[{"nick":"Tim","message":"Hallo","time":"06.07.2012 13:26:41"}]}

My Objective C Code:

NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:@"..URL.."];
NSArray *messages = [data objectForKey:@"messages"];
NSDictionary *json = [NSJSONSerialization
                           JSONObjectWithData:messages
                                      options:NSJSONReadingMutableLeaves
                                        error:&error];
NSString *nick = [json objectForKey:@"nick"];
NSString *message = [json objectForKey:@"message"];

But this doesn´t work and I don´t know what to do!

David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
  • Think you mixed up your code a bit there. You are calling `objectForKey:` on the `NSData` object. – Michael Boselowitz Jul 06 '12 at 12:56
  • 2
    Don't actually see a question in there. When you say "doesn't work", what do you mean? Is there an error? Incorrect results? What have you tried? Gotta give us more if you want help. – John T Jul 06 '12 at 12:57
  • I need NSString instead of NSData or what??? – user1480467 Jul 06 '12 at 13:08
  • You are calling `objectForKey:` on the `NSData` before you use `NSJSONSerialization`. I'd be surprised if `messages` in this case was anything but `nil`. Furthermore, ahwulf's answer is correct once that code is flipped around. – Michael Boselowitz Jul 06 '12 at 14:58

1 Answers1

2

Your JSON is a dictionary of arrays of dictionaries, i.e. {[{}]}

NSArray *messages = [json objectForKey:@"messages"];
NSString* nick = [[messages objectAtIndex:0]objectForKey:@"nick"]
ahwulf
  • 2,584
  • 15
  • 29