0

我在这里做公认的答案,但它对我不起作用。我明白了NULL

我从一个数组生成 JSON:

    NSError* error;
    NSData *result =[NSJSONSerialization dataWithJSONObject:self.fileNamesListForUpload options:0 error:&error];
    NSString *displayJson = [[NSString alloc] initWithData:result
                                             encoding:NSUTF8StringEncoding];
     NSLog(@"json result %@",displayJson);

这打印["sample.pdf","sample-1.pdf"]然后我使用以下命令发布字符串

curl -F "nameList=["sample.pdf","sample-1.pdf"]" 网址

在我的 php 代码中;

//get json string
    $jsonString = $_POST["nameList"];
    var_dump($_POST["nameList"]);
    $arrayOfNames=json_decode($jsonString,true);
    var_dump($arrayOfNames);
    echo "ArrayOfNames: ",$arrayOfNames,"\n";

结果是;

string(25) "[sample.pdf,sample-1.pdf]"
NULL
ArrayOfNames:

或者如果我添加引号 '' 我得到;

string(27) "'[sample.pdf,sample-1.pdf]'"
NULL

为什么当我使用 _POST 时会忽略“”?[sample.pdf,sample-1.pdf]我发帖["sample.pdf","sample-1.pdf"]

如何解析 json 字符串并将其放入数组中?

4

3 回答 3

2

如果您发送请求为curl -F "nameList=["sample.pdf","sample-1.pdf"]" url

var_dump($_POST["nameList"])将返回string(25) "[sample.pdf,sample-1.pdf]"

如果您发送为curl -F 'nameList=["sample.pdf","sample-1.pdf"]' url

var_dump($_POST["nameList"])将返回string(33) "[\"sample.pdf\",\"sample-1.pdf\"]"

您可以使用第二个选项并从字符串中删除反斜杠。

<?php
    $jsonString = $_POST["nameList"];
    var_dump($jsonString);
    $jsonString = str_replace("\\", "", $jsonString);
    var_dump($jsonString);
    $arrayOfNames=json_decode($jsonString,true);
    var_dump($arrayOfNames);
?>

Objective-C 方面:

NSData *jsonArray =[NSJSONSerialization dataWithJSONObject:@[@"sample.pdf", @"sample-1.pdf"] options:0 error:nil];
NSString *stringFromJsonArray = [[NSString alloc] initWithData:jsonArray encoding:NSUTF8StringEncoding];
NSLog(@"%@", stringFromJsonArray); //["sample.pdf","sample-1.pdf"]

NSString *requestString = [NSString stringWithFormat:@"nameList=%@", stringFromJsonArray];
NSLog(@"%@", requestString); //nameList=["sample.pdf","sample-1.pdf"]

NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/t.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *responseData = [NSURLConnection  sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithBytes:responseData.bytes length:responseData.length encoding:NSUTF8StringEncoding];
NSLog(@"%@", responseString);
/*
string(33) "[\"sample.pdf\",\"sample-1.pdf\"]"
string(29) "["sample.pdf","sample-1.pdf"]"
array(2) {
  [0]=>
  string(10) "sample.pdf"
  [1]=>
  string(12) "sample-1.pdf"
} */
于 2013-05-10T16:19:40.263 回答
0

您忘记对 JSON 字符串进行 urlencode 导致 $_POST 解压缩其中的一部分,您不希望这样。

我不知道如何在 Obj-C 中进行 url 编码,但在 PHP 中是:

"nameList=" . urlencode($json_string);

然后$_POST["nameList"]应该包含字符串["sample.pdf", "sample.pdf"],你可以json_decode

于 2013-05-10T14:14:43.047 回答
0

我最终放弃了 _POST 请求并使用了它;

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);


sendResponse(200, json_encode($decoded));

在 Objective-c 部分

NSError* error;
    NSData *result =[NSJSONSerialization dataWithJSONObject:self.fileNamesListForUpload options:0 error:&error];
    NSString *displayJson = [[NSString alloc] initWithData:result
                                             encoding:NSUTF8StringEncoding];
    NSLog(@"json result %@",displayJson);


    if ([self.fileNamesListForUpload count]>=1) {
        //send file upload request here
        NSURL* url = [NSURL URLWithString:deleteExtraFilesIn];
        __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];


        [request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
        [request addRequestHeader:@"Content-Type" value:@"application/json"];
        [request appendPostData:[displayJson  dataUsingEncoding:NSUTF8StringEncoding]];


        [request setCompletionBlock:^
         {
            if (request.responseStatusCode == 200) {

             //succesfully inserted row
                 NSError* error;
                 NSString *responseString = [request responseString];
                 NSDictionary* json =     [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding]
                                                                          options: NSJSONReadingMutableContainers
                                                                            error: &error];

                 NSLog(@"recieved dict %@",json);


             }
}];

        [request setFailedBlock:^
         {
             //NEED RETURN FALSE
             //hide progress hud
         }];

        //start sync
        [request setDelegate:self];
        [request startAsynchronous];
    }
于 2013-05-10T19:03:56.630 回答