我創建了一個簡單的PHP文件輸出JSON字符串:JSON來的NSDictionary從HTTP POST請求
<?
$test = $_POST["hashcode"];
if ($ttest != "")
{
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'couponcode' => $test);
echo json_encode($arr);
}
?>
我想使用Objective-C語言來檢索該JSON並將其解析爲一個的NSDictionary。我目前使用JSON框架,但它不適合我。
NSHTTPURLResponse * response;
NSError * error;
NSString *post = @"hashcode=asdf1234fdsa";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"www.ski-inndronten.nl/json.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSData *testJSON = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *jsonString = [testJSON JSONRepresentation];
NSLog(@"String = %@",jsonString);
NSDictionary *testDict = [jsonString JSONValue];
NSLog(@"testDict = %@",testDict);
我希望你能幫助我,因爲我不知道我做錯了什麼。 (我輸出NULL對象)
只要放一些斷點即可。響應(testJSON數據)在請求後沒有任何值。 – Ilanchezhian