iPhone App - JSONKit objectFromJSONString返回null

时间:2011-07-14 10:57:59

标签: php iphone xcode asihttprequest

您好我有一个使用ASIFormDataRequest将变量发布到php文件的iPhone应用程序。然后,php文件以关联数组的形式从远程数据库返回一组元组。

我使用objectFromJSONString来反序列化json数据(使用JSONKit框架),但是pon打印出数据,我得到null。这是我的代码:

+(NSDictionary*)getQuestions:(NSString*)sectionId from: (NSString*) url{
    NSDictionary *questions;
    NSURL *link = [NSURL URLWithString:url];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
    [request setPostValue:sectionId forKey:@"section"];
    NSError *error = [request error];
    [request setDelegate:self];
[request setDidFinishSelector:@selector(requestFinished:)];
    [request startAsynchronous];

    if (!error) {       
        //NSString *response = [request responseString];
        //store them in the dictionary
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        questions = [json objectFromJSONString];    
        NSLog(@"%@",questions); //prints null
        [json release];
        [request release];      
    }else{
        //UIAlertView to warn users there was an error
    }               

    return questions;   
}

//doesn't work
- (void)requestFinished:(ASIHTTPRequest *)request
{
    //NSString *response = [request responseString];
    NSLog(@"hello"); //never prints
}

@end

@implementation dbQuestionGetterViewController
@synthesize questions;

-(void)viewDidLoad{
    //code to initialise view
    NSDictionary* arr = [dbConnector getQuestions:@"2" from:@"http://dev.speechlink.co.uk/David/get_questions.php"];
    self.questions = arr;
    [super viewDidLoad];
}
@end

我尝试过使用ASIHTTPRequest calback委托(didFinishSelector)

更新:

这是php的链接。单击它时,您可以看到它正确输出JSON:

http://dev.speechlink.co.uk/David/get_questionstest.php

这是php:

<?php

//connect to database

$dbh = mysql_connect ("localhost", "abc", "123") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh); 

$query = mysql_query("SELECT * FROM Questions WHERE sectionId = 1") or die("Error: " . mysql_error());;

$rows = array();
while($r = mysql_fetch_assoc($query)) {
  $rows[] = $r;
}
//echo '{"questions":'.json_encode($rows).'}';
echo json_encode($rows);
mysql_close();

?>

1 个答案:

答案 0 :(得分:0)

如果您传入的字符串无效,则返回nil。

可能会发生两件事:

(1)你没有正确解析服务器的响应 - 尝试输出json字符串以查看你认为它是什么。

NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", json);

(2)服务器没有发送正确的JSON - 尝试在浏览器中打开URL并确保它正确形成。