目的-C-> JSON-> PHP数组 [英] Objective-C->JSON->PHP Array

查看:120
本文介绍了目的-C-> JSON-> PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在挣扎与本作的最后几天;我想发布一个数组到PHP。我可以成功发送,但它不是一个后可变(我尝试使用可变密钥JSON......有了这个code,我收到PHP中的数组拍摄于:

目标-C

  NSError *错误;
的NSDictionary * jsonDictionary = [NSDictionary的dictionaryWithObjects:[NSArray的arrayWithObjects:@一,@二,@三,零] forKeys:[NSArray的arrayWithObjects:@一,@B,@C,零]];
NSArray的* jsonArray = [NSArray的arrayWithObject:jsonDictionary];
NSData的* jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray选项:NSUTF8StringEncoding错误:&放大器;错误]
NSMutableURLRequest *请求= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@?somewebservicelocation / arrayTest.php JSON =]];
[申请的setValue:@应用程序/ JSONforHTTPHeaderField:@的Content-Type];
[要求setHTTPMethod:@POST];
[要求setHTTPBody:jsonData];
NSData的* returnData = [NSURLConnection的sendSynchronousRequest:要求returningResponse:无错误:无];
* NSString的响应= [[NSString的页头] initWithData:returnData编码:NSUTF8StringEncoding];
的NSLog(@回应:%@,响应);

PHP

  $ =处理的fopen('PHP://输入','R');
    $阵列=与fgets($处理);
    回声$阵列;
    如果(使用isset($阵列))
    {
        回声成功;
    }
    其他
    {
        回声失败;
    }

如果我用这个PHP,使用_POST,我没有得到任何的爱:

  $ rawJsonData = $ _ POST ['JSON'];
$阵列= json_de code(的stripslashes($ rawJsonData),TRUE);
回声$阵列;
如果(使用isset($阵列))
{
    回声成功;
}
其他
{
    回声失败;
}

...我已经在这几天 - 遍布堆栈溢出,并理解我需要包括在请求体中的变量和数据,但我不能得到它的工作。我究竟做错了什么?你怎么去这个不同?从这个头痛救我......


解决方案

在PHP端,我用类似的东西到你的第一个例子:

 < PHP$处理=的fopen(PHP://输入,RB);
$ HTTP_RAW_POST_DATA ='';
而(!的feof($处理)){
    。$ HTTP_RAW_POST_DATA = FREAD($处理,8192);
}
FCLOSE($处理);//做你想要做什么用
//
//用于诊断目的,我只是要取消code,确保我有一个数组,
//和JSON,包括状态,code,和原来的请求作出响应$ post_data = json_de code($ HTTP_RAW_POST_DATA,真正的);如果(is_array($ post_data))
    $响应=阵列(状态=>中确定,code=大于0,原始请求=> $ post_data);
其他
    $响应=阵列(状态=>中的错误,code= -1个,original_request=> $ post_data);$处理= json_en code($响应);
回声$处理;?>

然后在iOS方面,我使用:

<为pre> //创建字典(或阵列)*的NSDictionary字典= @ {@一:@一,@B:@二,@C:@三};
NSError *误差=零;
NSData的*数据= [NSJSONSerialization dataWithJSONObject:字典选项:0错误:&放大器;错误]
如果(错误)
    的NSLog(@%S:JSON EN code错误:%@,__FUNCTION__,错误);//创建请求NSURL * URL = [NSURL URLWithString:@your.url.here];
NSMutableURLRequest *请求= [NSMutableURLRequest requestWithURL:URL]
[要求setHTTPMethod:@POST];
[申请的setValue:@应用程序/ JSON的;字符集= UTF-8forHTTPHeaderField:@的Content-Type];
[要求setHTTPBody:数据]//发出请求NSURLResponse *响应=零;
NSData的* returnData = [NSURLConnection的sendSynchronousRequest:请求returningResponse:安培;响应错误:放大器;错误]
如果(错误)
    的NSLog(@%S:NSURLConnection的错误:%@,__FUNCTION__,错误);//检查响应* NSString的responseString = [[NSString的页头] initWithData:returnData编码:NSUTF8StringEncoding];
的NSLog(@responseString:%@,responseString);

我刚刚测试了这个往返,并能正常工作。


如果你有决心使用 _ POST 技术,有什么工作对我来说是设置中的数据是 JSON =%@ ,如:

 的NSDictionary *词典= ...
NSData的*数据= [NSJSONSerialization dataWithJSONObject:字典选项:0错误:&放大器;错误]
* NSString的字符串= [[NSString的页头] initWithData:数据编码:NSUTF8StringEncoding];
如果(错误)
    的NSLog(@%S:JSON EN code错误:%@,__FUNCTION__,错误);NSURL * URL = [NSURL URLWithString:@your.url.here];
NSMutableURLRequest *请求= [NSMutableURLRequest requestWithURL:URL][要求setHTTPMethod:@POST];
* NSString的PARAMS = [的NSString stringWithFormat:@JSON =%@,
                    [字符串stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData的* paramsData = [PARAMS dataUsingEncoding:NSUTF8StringEncoding];
[申请的addValue:@8位forHTTPHeaderField:@内容传输编码];
[申请的addValue:@应用程序/ x-WWW的形式urlen codeDforHTTPHeaderField:@的Content-Type];
[要求setHTTPBody:paramsData];//现在发送请求,像前

和PHP的解析它很像你有:

  $ HTTP_RAW_POST_DATA = $ _ POST ['JSON'];$ post_data = json_de code(的stripslashes($ HTTP_RAW_POST_DATA),TRUE);如果(is_array($ post_data))
    $响应=阵列(状态=&gt;中确定,code=大于0,原始请求=&GT; $ post_data);
其他
    $响应=阵列(状态=&gt;中的错误,code= -1个,original_request=&GT; $ post_data);$处理= json_en code($响应);
回声$处理;

I've been struggling with this for the last few days; I am trying to post an array to PHP. I can successfully send it, but it's not taken in with a post-variable (I am trying to use the variable key "json"... With this code, I receive the array in php:

Objective-C

NSError *error;
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: @"one", @"two", @"three", nil] forKeys: [NSArray arrayWithObjects: @"a", @"b", @"c", nil]];
NSArray *jsonArray = [NSArray arrayWithObject:jsonDictionary];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray options:NSUTF8StringEncoding error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"somewebservicelocation/arrayTest.php?json="]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"response: %@",response);

PHP

$handle = fopen('php://input','r');
    $array = fgets($handle);
    echo $array;
    if(isset($array))
    {
        echo "success";
    }
    else
    {
        echo "failure";
    }

If I use this PHP, using _POST, I get no love:

$rawJsonData = $_POST['json'];
$array = json_decode(stripslashes($rawJsonData),true);
echo $array;
if(isset($array))
{
    echo "success";
}
else
{
    echo "failure";
}

...I've been at it for several days - all over Stack Overflow, and understand I need to include the variable and data in the body of the request, but I just can't get it to work. What am I doing wrong? How do you go about this differently? Save me from this headache...

解决方案

On the PHP side, I've used something similar to your first example:

<?php

$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);

// do what you want with it
//
// For diagnostic purposes, I'm just going to decode, make sure I got an array, 
// and respond with JSON that includes status, code, and the original request

$post_data = json_decode($http_raw_post_data,true);

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;

?>

And then on the iOS side, I use:

// create the dictionary (or array)

NSDictionary *dictionary = @{@"a": @"One", @"b": @"Two", @"c": @"Three"};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
if (error)
    NSLog(@"%s: JSON encode error: %@", __FUNCTION__, error);

// create the request

NSURL *url = [NSURL URLWithString:@"your.url.here"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:data];

// issue the request

NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
    NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);

// examine the response

NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);

I just tested this round trip, and it works fine.


If you are determined to use the _POST technique, what works for me is to set the the data to be json=%@, such as:

NSDictionary *dictionary = ...
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (error)
    NSLog(@"%s: JSON encode error: %@", __FUNCTION__, error);

NSURL *url = [NSURL URLWithString:@"your.url.here"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
NSString *params = [NSString stringWithFormat:@"json=%@",
                    [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *paramsData = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:paramsData];

// now send the request, like before

And the PHP to parse it is much like you had:

$http_raw_post_data = $_POST['json'];

$post_data = json_decode(stripslashes($http_raw_post_data),true);

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;

这篇关于目的-C-&GT; JSON-&GT; PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆