如何使用Alomofire SWIFT在post api中发送JSON

时间:2016-08-08 09:37:00

标签: iphone json swift alamofire

我需要在swift中使用alamofire在post api中发送JSON格式。需要发送的方式数据是

{
"data": [{
    "id": "1015683997",
    "name": "Pawel"
}, {
    "id": "108350039247",
    "name": "Randeep"
}, {
    "id": "115607797616",
    "name": "Mohit"
}]
}

我现在能够生成的方式是:

["data": {
data =     (
            {
        id = 101583997;
        name = "Pawel";
    },
            {
        id = 108359247;
        name = "Randeep";
    },
            {
        id = 11567616;
        name = "Mohit ";
    }
);
}
]

使用下面提到的方法生成json格式。

for i in 0..<self.arrFriendsList.count
    {

        let dictFrndList:[String: AnyObject] = [
            "id" : arrFriendsList[i].valueForKey("id")!,"name" : arrFriendsList[i].valueForKey("name")!
            ]

        arrFrndList.addObject(dictFrndList)
    }

然后,

let dictFBFrndList: [String: AnyObject] = [

        "data":arrFrndList
    ]

然后,

let params: [String: AnyObject] = [

        "access_token" : accessToken,
        "data":dictFBFriends
    ]

所以,请指导我。我已经花了一天多的时间。提前谢谢。

3 个答案:

答案 0 :(得分:0)

我是第二个Larme所说的,你应该在带有关键“数据”而不是dictFBFrndList的params上发布“arrFrndList”。

答案 1 :(得分:0)

let options = NSJSONWritingOptions()
    let data = try? NSJSONSerialization.dataWithJSONObject(parameters, options: options)
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string:"http:/myurl.com")

    if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String {
        print(str)
    }
    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    mutableURLRequest.setValue("your_access_token", forHTTPHeaderField: "Authorization")
    mutableURLRequest.HTTPBody = data
    mutableURLRequest.HTTPMethod = "POST"

    Alamofire.request(mutableURLRequest).responseJSON(){
        json in
        if let value = json.result.value {
            let _json = JSON(value)
            if (!_json.isEmpty){
                print(_json)
            }
        }
    }

您可以查看如何查看您的JSON数组此代码。看第5个单元代码。此代码将在输出屏幕中为您编写json数组,您可以从那里进行coppy并粘贴到here,然后您将看到如何发送数据。

也许这种方式可以帮到你。

答案 2 :(得分:0)

以这种方式管理

let jsonData = try! NSJSONSerialization.dataWithJSONObject(arrFriendsList, options: NSJSONWritingOptions.PrettyPrinted)

    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String

    print(jsonString)

    let params: [String: AnyObject] = [

        "access_token" : accessToken,
        "data":jsonString
    ]