-1

When outputting the entire parsed JSON object it works fine, however when trying to output the value of a key it comes up with (null)

The parsing code:

-(NSString *)getNews{

__block NSString *strReturn;

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://URL/URL.json"]];

__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                           json = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:nil];

                               NSLog(@"Async JSON news: %@", json[@"ID"]);

                           //strReturn = json[@"ID"];
                       }];
return strReturn = @"Hello";

}

This here is from the JSON output file on the server;

[{"ID":"1","Item Description":"Test News Item Active","News Text":"This is a test news story.\r\n\r\nit should have a few line breaks.\r\n\r\nbut that's about it.","Valid From":"2014-05-23 00:00:00","Valid To":"2014-09-30 23:59:59"}]

Can anybody tell me why it is not finding the value of key ID?

Ian Taylor
  • 179
  • 1
  • 5
  • 18
  • 1
    Go to json.org and learn the JSON syntax. This only takes 5-10 minutes, and then you will see that what you have above is an ARRAY containing a single JSON OBJECT. – Hot Licks Jul 22 '14 at 16:57
  • Also, the `error` parm is there for a reason, and if you ignore it I will viciously downvote you. – Hot Licks Jul 22 '14 at 16:59
  • Thanks everyone, I have noted what you have all said, however I have another block the same for reading JSON (which isnt inside an array, so that must be the issue) that works. I will try looking into retrieving the value of an object in an array – Ian Taylor Jul 22 '14 at 17:06
  • Also, your method won't be able to return anything from your response the way you have it set up. Look into using callback blocks. – CrimsonChris Jul 22 '14 at 17:07

1 Answers1

1

The JSON Dictionary is inside an array. So you have to reference it correctly:

NSLog(@"Async JSON news: %@", [[json objectAtIndex:0] objectForKey:@"ID"]);
Julian F. Weinert
  • 7,474
  • 7
  • 59
  • 107
  • Hey thanks for the answer! Only problem with this, is im now getting the error `No visible @interface for 'NSDictionary' declares selector 'objectAtIndex'` – Ian Taylor Jul 22 '14 at 17:02
  • 1
    Because you are using an NSDictionary pointer for what is actually an NSArray. – CrimsonChris Jul 22 '14 at 17:05