简体   繁体   English

Objective-C Json字符串到PHP数组

[英]Objective-C Json String to PHP Array

I am doing accepted answer here but it doesn't work for me. 我在这里做了接受的答案但它对我不起作用。 I get NULL . 我得到NULL

I produce JSON from an array with: 我从一个数组生成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);

this prints ["sample.pdf","sample-1.pdf"] then I use following command to post the string 这打印["sample.pdf","sample-1.pdf"]然后我使用以下命令发布字符串

curl -F "nameList=["sample.pdf","sample-1.pdf"]" url curl -F“nameList = [”sample.pdf“,”sample-1.pdf“]”url

In my php code; 在我的PHP代码中;

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

Result is; 结果是;

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

or if I add quotes '' I get; 或者如果我添加引号''我得到;

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

Why "" are dismissed when I use _POST? 当我使用_POST时,为什么“”被解雇? [sample.pdf,sample-1.pdf] I am posting ["sample.pdf","sample-1.pdf"] ? [sample.pdf,sample-1.pdf]我发帖["sample.pdf","sample-1.pdf"]

How can I parse json string and put it into an array? 如何解析json字符串并将其放入数组?

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

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

If you send as curl -F 'nameList=["sample.pdf","sample-1.pdf"]' url 如果你发送curl -F 'nameList=["sample.pdf","sample-1.pdf"]' url

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

You can use second option and remove backslashs from string. 您可以使用第二个选项并从字符串中删除反斜杠。

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

Objective-C side: 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"
} */

You've forgotten to urlencode the JSON string causing the $_POST to unpack part of it, you don't want that. 您忘记了对JSON字符串进行urlencode,导致$ _POST解压缩部分内容,您不希望如此。

I don't know how to do url encoding in Obj-C but in PHP it is: 我不知道如何在Obj-C中进行url编码,但在PHP中它是:

"nameList=" . urlencode($json_string);

Then $_POST["nameList"] should contain the string ["sample.pdf", "sample.pdf"] , and you can json_decode that. 那么$_POST["nameList"]应该包含字符串["sample.pdf", "sample.pdf"] ,你可以json_decode那个。

I ended up givin up _POST request and use this; 我最终收到_POST请求并使用它;

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


sendResponse(200, json_encode($decoded));

in Objective-c part 在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];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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