iOS JSON响应两次,JSON为Null


iOS JSON Response twice, JSON Null

为什么我的json响应在某些情况下重复两次(无法隔离),从而导致我的jsonData为(null)。我对Android使用相同的php,但只有我的iOS看到了这个问题。这是我的objective-C代码,它会产生两次响应——有时是:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSLog(@"Response code: %d", [response statusCode]);
        if ([response statusCode] >=200 && [response statusCode] <300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);
            SBJsonParser *jsonParser = [SBJsonParser new];
            NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
            NSLog(@"jsonData: %@",jsonData);

这里是php:

//retrieve the login details via POST
$username = $_POST ['username'];
$query = mysql_query ("SELECT * FROM inputs
WHERE user = '$username' AND ts = (SELECT MAX(`ts`)FROM inputs WHERE user =    '$username')");
//create a while loop that places the returned data into an array
while ($list = mysql_fetch_assoc($query)){
//store the returned data into a variable
$output = $list;
//encode the returned data in JSON format
echo json_encode($output);
}
//close connection
mysql_close();
?>

构建输出数组,然后输出json。可能发生的情况是,您第一次发送有效的json,然后当您继续ech时,它变得无效,因为您的字符串如下:

{test: 1}{hello: 2}

不是有效的json。

$output = array();
//create a while loop that places the returned data into an array
while ($list = mysql_fetch_assoc($query)){
//store the returned data into a variable
$output[] = $list;
}
//encode the returned data in JSON format
echo json_encode($output);