ios - Objective-C Json String to PHP Array -
i doing accepted answer here doesn't work me. null.
i produce json 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"] use following command post string
curl -f "namelist=["sample.pdf","sample-1.pdf"]" url
in 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 add quotes '' get;
string(27) "'[sample.pdf,sample-1.pdf]'" null why "" dismissed when use _post? [sample.pdf,sample-1.pdf] posting ["sample.pdf","sample-1.pdf"] ?
how can parse json string , put array?
if send request curl -f "namelist=["sample.pdf","sample-1.pdf"]" url
var_dump($_post["namelist"]) return string(25) "[sample.pdf,sample-1.pdf]".
if send curl -f 'namelist=["sample.pdf","sample-1.pdf"]' url
var_dump($_post["namelist"]) return string(33) "[\"sample.pdf\",\"sample-1.pdf\"]".
you can use second option , remove backslashs 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" } */
Comments
Post a Comment