[英]Send json data to php returning null
我正在尝试通过json格式将一组数据(字典中的字典)发送到服务器端的php文件,以便稍后将数据存储到MySQL数据库中。 但是,看起来php接收的数据对象始终为null。
以下是Objective-C行:
NSURL *url = [NSURL URLWithString:@"http://myaddress/upload.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:self.sentData];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);
这是php行:
<?php
$json_data=file_get_contents('php://input');
$post_data = json_decode($json_data);
if (is_array($post_data))
$response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
$response = array("status" => "error", "code" => -1, "original_request" => $post_data);
$processed = json_encode($response);
echo $processed;
?>
Xcode上的调试信息如下:
2015-07-19 17:34:35.900 PhpPostTest[1531:557248] responseString: {"status":"error","code":-1,"original_request":null}
看起来连接正常,但响应字符串表示php端收到的数据为空。 任何人都可以在这里提出潜在的问题吗?
只要您尝试解码的JSON格式不正确, json_decode()
将返回NULL
。
你可以运行echo $json_data;
验证您的JSON实际上是JSON。
默认情况下,json_decode不会将解码后的字符串作为数组返回。 如果你想让它返回一个数组,你必须通过将函数的第二个参数设置为true来指定它。
json_decode($json_data, true);
否则在这种情况下json_decode可以返回stdClass对象。 当然,is_array检查将评估为false。
还要确保传递给json_decode函数的数据编码为UTF-8。 它代表一个有效的json字符串,否则你将得到null作为结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.