简体   繁体   中英

Send json data to php returning null

I'm trying to send an array of data (dictionaries in side) through json format to a php file on the server side, so that later on the data will be stored into a MySQL database. However, it looks like that the data object received by php is always null.

Here are the Objective-C lines:

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);

Here are the php lines:

<?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;

?>

The debugging message on Xcode is as below:

2015-07-19 17:34:35.900 PhpPostTest[1531:557248] responseString: {"status":"error","code":-1,"original_request":null}

Looks like the connection is ok, but the response string indicates that the data received by php side is null. Can anybody suggest what's potential issue here?

json_decode() will return NULL whenever the JSON you are trying to decode is malformed.

You can run echo $json_data; to verify that your JSON is actually JSON.

By default json_decode would not return the decoded string as an array. If you want it tu return an array you must specify it by setting the second parameter of the function to true.

json_decode($json_data, true);

Otherwise in this case json_decode could return a stdClass object. And of course the is_array check will evaluate to false.

Also make sure the data passed to the json_decode function is encoded as UTF-8. And it represents a valid json string, otherwise you'll get null as a result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM