2011-10-31 108 views
-1

我创建了一个简单的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对象)

+0

只要放一些断点即可。响应(testJSON数据)在请求后没有任何值。 – Ilanchezhian

回答

1

确定有两个误区:

第一,你忘了添加的“http://”在你的URL字符串前面。如果您不这样做,请求将失败并返回数据为零。

第二,你发送不正确的应用程序/ json内容类型,如果你这样做,PHP将返回一个无效的答案。只需删除此设置并返回的代码将是正确的。

顺便说一句,你可以通过登录返回的数据如下方便您调试:


NSData *testJSON = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
NSLog(@"%@",[[NSString alloc] initWithData:testJSON encoding:NSUTF8StringEncoding]); 

如果你做这两个更正,答案将正确地返回。

+0

我在这个网站上发布了代码,并将变量$ test写为$ ttest。如果json.php没有收到帖子请求,它不会输出任何内容。我更新了te代码,它总是输出一些东西。不幸的是,NSLog仍然输出NULL表示。 –

+0

看到我更正的答案:纠正后工作发现和代码测试(我没有测试您的JSON转换,因为我没有使用您的代码中的JSON类,所以我限制了我的支票控制POST返回的字符串) – viggio24

+0

Thx,这为我工作! –