SpaceDust__
SpaceDust__

Reputation: 4914

Objective-C Json String to PHP Array

I am doing accepted answer here but it doesn't work for me. I get NULL.

I produce JSON from an array with:

    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

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

In my php code;

//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? [sample.pdf,sample-1.pdf] I am posting ["sample.pdf","sample-1.pdf"] ?

How can I parse json string and put it into an array?

Upvotes: 0

Views: 881

Answers (3)

SpaceDust__
SpaceDust__

Reputation: 4914

I ended up givin up _POST request and use this;

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


sendResponse(200, json_encode($decoded));

in Objective-c part

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];
    }

Upvotes: 0

ifau
ifau

Reputation: 2120

If you send request as curl -F "nameList=["sample.pdf","sample-1.pdf"]" url

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

If you send as curl -F 'nameList=["sample.pdf","sample-1.pdf"]' url

var_dump($_POST["nameList"]) will return 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:

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"
} */

Upvotes: 2

Halcyon
Halcyon

Reputation: 57729

You've forgotten to urlencode the JSON string causing the $_POST to unpack part of it, you don't want that.

I don't know how to do url encoding in Obj-C but in PHP it is:

"nameList=" . urlencode($json_string);

Then $_POST["nameList"] should contain the string ["sample.pdf", "sample.pdf"], and you can json_decode that.

Upvotes: 0

Related Questions