Swift HTTP POST 2D数组

时间:2015-04-14 12:52:08

标签: arrays swift http post request

问题是:以哪种格式将此数组发送到远程URL? JSON还是数组?

是否可以将其作为简单数组发送?

我想要做的是,将2d数组发送到url。该数组如下所示:

[
   "deviceID" => "123456789"
   "answers" => array(
        1=>"a",
        2=>"b"
        ...
   )
]

现在有点代码:

我有以下词典:

var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary => [2: B, 1: B, 3: B]

现在,我想创建另一个Dictionary,例如:["deviceID", "123456789"],稍后将这两个Dictionaries连接到一个,JSON编码结果数组。

我怎么能意识到它?

对于我使用的POST:

var URL: NSURL = NSURL(string: "http://example.com/en/check-answers")!
        var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
        request.HTTPMethod = "POST"
        var bodyData = // a JSON encode here

        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
                {
                    (response, data, error) in
                    println(NSString(data: data, encoding: NSUTF8StringEncoding))
        }

1 个答案:

答案 0 :(得分:1)

您可以使用answers对象和deviceID键/值对构建新词典:

let answers = ["a", "b", "c"]  // build this any way you want
let device = "123456789"

let payload = ["answers" : answers, "deviceID" : device]
let body = try! NSJSONSerialization.dataWithJSONObject(payload, options: [])

let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = body

// now issue request

创建看起来像的JSON:

{"answers":["a","b","c"],"deviceID":"123456789"}

如果您希望在服务器获取它时看到它,您可以使用PHP代码并将其打印出来:

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

    $body = json_decode($raw_post_data, true);
    header("Content-Type: text/plain");
    print_r($body);
?>

看起来像:

Array
(
    [answers] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [deviceID] => 123456789
)

显然,我通常不会print_rvar_dump,而是会构建一个JSON响应(为application/json标头设置Content-Type,使用{{1构建响应等),但我想在更多的本机PHP语法中显示关联数组。但希望这说明了这个想法。


顺便说一下,如果你想真正代表json_encode本身作为字典,你也可以这样做,例如:

answers

请注意,密钥let answers = ["1" : "a", "2" : "b", "3" : "c"] 12必须是字符串,而不是数字(它是JSON的约束,而不是Swift中的字典)。

无论如何,生成的JSON看起来像

3

在PHP中,这看起来像:

{"answers":{"2":"b","1":"a","3":"c"},"deviceID":"123456789"}