将Dictionary转换为Json以传递Alamofire

时间:2017-06-16 06:12:08

标签: ios json dictionary swift3

我有一个字典,其中key为用户名,值为email。我想使用Alamofire发送到api我不知道如何处理这个问题,因为我想将多个用户发送到api立即保存。

词典

var selectedMembers = [String: String]()

此词典中保存的数据附加在表视图中的不同VC中,我们可以在其中选择要在词典中追加的用户数。 现在我需要将这个字典转换为json formate,通过alamofire发送到api。

Json Formate

"users": [
        {
          "user_email": "abc@gmail.com",
          "user_name": "abc"
        }, 
        {
          "user_email": "abc2@gmail.com",
          "user_name": "abc2"
        }   
   ]

Alamofire Code

let parameters: Parameters = [
            "users" : [
               [
                "user_name" : "user_name goes here",
                "user_email" : "user_email goes here"
               ]
            ]
        ]

        Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in

        }

我如何解决问题

我创建了一个函数,用于打印我想要的数据并将其放在Alamofire参数中。

var selectedMembers = [String: String]()
var smembers = [AnyObject]()
var selected = [String: String]()

if selectedMembers.isEmpty == false {
        for (key, value) in selectedMembers {
            selected = ["useremail": key, "catagory": value]
            smembers.append(selected as AnyObject)
        }
    }

let jsonData = try? JSONSerialization.data(withJSONObject: smembers, options: JSONSerialization.WritingOptions())
let jsonString = NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue)

let parameters: Parameters = [
            "users" : jsonString as AnyObject
        ]

        Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in

        }

3 个答案:

答案 0 :(得分:2)

您只需创建字典数组(用户),目前您将user的值设为Dictionary而不是Array

let parameters: Parameters = [
    "users" : [
        [
            "user_name" : "abc",
            "user_email" : "abc@gmail.com"
        ],
        [
            "user_name" : "abc2",
            "user_email" : "abc2@gmail.com"
        ]
    ]
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in

}

答案 1 :(得分:0)

如果您的网络API要求发布数据以JSON格式发送,那么下面写入的方法是一种方法。

func calltheAPIToSendSelectedUser () {
    let parameters: [String: Any] = [
        "users" : [
            [
                {
                    "user_name" : "user1_name goes here",
                    "user_email" : "user1_email goes here"
                },
                {
                    "user_name" : "user2_name goes here",
                    "user_email" : "user2_email goes here"
                },
                {
                    "user_name" : "user3_name goes here",
                    "user_email" : "user3_email goes here"
                },
            ]
        ]
    ]

    var request = URLRequest(url: URL(string: "YourApiURL")!)
    request.httpMethod = "POST"
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [.prettyPrinted])
    Alamofire.request(request).responseJSON { response in

    }
}

答案 2 :(得分:0)

这是我的解决方案,用于使用Alamofire调用POST并传入一组字典值作为参数arg。 注意用户'包含值词典的键。

    let dict: NSMutableDictionary = [:]
    dict["facebook_id"] = "1234559393"
    dict["name"] = "TestName"
    dict["email"] = "TestEmailID"

    let params: Parameters = [
        "user": dict
    ]

    Alamofire.request("YOURURL", method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON(completionHandler: { (response) in
                            switch response.result {
            case .success:
                print("succeeded in making a Facebook Sign up REST API. Now going to update user profile"
                break
            case .failure(let error):
                return
                    print(error)
            }
        })

在您向字典添加项目的位置,您可以在此处检查nil值并避免根据需要添加,从而使其动态化。