使用Alamofire发布复杂数组

时间:2016-02-01 17:15:07

标签: ios swift alamofire

我将使用Alamofire的复杂动态数组发布到我的REST API时遇到问题。我想发布这样的内容;

let parameters = [
        "A": "a",
        "B": myObject.getStringValue(),
        "C": myDate.timeIntervalSince1970,
        "D": myObject2.getStringValue(),
        "E": MyComplexData
    ]; 
Alamofire.request(.POST, "http://myrestapi.com/myaction", parameters: parameters);

myComplexData是一个类似数组的变量,我想填充一个循环。我希望在服务器中接收数据,如下所示:

[
        "A": "a",
        "B": "b",
        "C": 24916942128,
        "D": "d",
        "E": [0: [ id: "firstID", value: "firstValue" ], 1: [ id: "secondID", value: "secondValue" ]]
    ]

我的问题是,我如何在MyComplexData中创建一个动态数组(或字典?)来接收这样的数据?

提前致谢, 罗伯特

1 个答案:

答案 0 :(得分:1)

最后,根据@Catalina T.答案,我用JSON编码数据做到了。完整代码:

    var myComplexData = Dictionary<String, String>();
    for i in previousCollectedDynamicDataArray {
        myComplexData[i.getID()] = i.getVal();
    }

    let parameters = [
        "A":"A",
        "B": myObject.getStringValue(),
        "C": myDate.timeIntervalSince1970,
        "D": myObject2.getStringValue(),
        "E": myComplexData
    ];

    Alamofire.request(.POST, "http://myrestapi.com/myaction", parameters: [ "data": objToJSONString(parameters) ]);

这是objToJSONString函数:

func objToJSONString(obj: AnyObject) -> String {
    guard   let data = try? NSJSONSerialization.dataWithJSONObject(obj, options: .PrettyPrinted),
            let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
    else {
        return "";
    }

    return jsonString as String;
}

服务器收到&#34;数据&#34; post变量内部的JSON编码数据。