【问题标题】:Send json data to php returning null将json数据发送到php返回null
【发布时间】:2015-07-19 22:49:45
【问题描述】:

我正在尝试通过 json 格式将一组数据(侧面的字典)发送到服务器端的 php 文件,以便稍后将数据存储到 MySQL 数据库中。但是,看起来php接收到的数据对象始终为空。

以下是 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端接收到的数据为null。谁能建议这里有什么潜在的问题?

【问题讨论】:

  • 我能看到你试图解码的 JSON 吗?
  • Jep,如果您尝试解析的 json 无效,则 json_decode 返回 null。所以 $json_data 可能包含无效的 json...你尝试解析它,$post_data 变为 null。

标签: php ios json


【解决方案1】:

只要您尝试解码的 JSON 格式不正确,json_decode() 就会返回 NULL

您可以运行 echo $json_data; 来验证您的 JSON 实际上是 JSON。

【讨论】:

    【解决方案2】:

    默认情况下,json_decode 不会将解码后的字符串作为数组返回。如果你希望它返回一个数组,你必须通过将函数的第二个参数设置为 true 来指定它。

    json_decode($json_data, true);
    

    否则在这种情况下 json_decode 可能会返回一个 stdClass 对象。当然,is_array 检查将评估为 false。

    还要确保传递给 json_decode 函数的数据被编码为 UTF-8。它代表一个有效的 json 字符串,否则你会得到 null 作为结果。

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多