Aman Chawla
Aman Chawla

Reputation: 229

Converting Dictionary to Json to pass parameters in Alamofire

I have a dictionary with key as username and value as email. Which i would like to send to an api using Alamofire i have no clue how to approach this problem as i am suppose to send multiple users to the api to save at once.

Dictionary

var selectedMembers = [String: String]()

The data saved in this dictionary is appended in a different VC from a table view where we can choose how many users we want to append in the dictionary. Now i need to convert this dictionary into json formate to send to the api through alamofire.

Json Formate

"users": [
        {
          "user_email": "[email protected]",
          "user_name": "abc"
        }, 
        {
          "user_email": "[email protected]",
          "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

        }

How i solved the Problem

i created a function that prints the the data how i want it and placed it in Alamofire parameters something like this.

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

        }

Upvotes: 1

Views: 5040

Answers (3)

Rads
Rads

Reputation: 11

Here's my solution that worked for invoking POST using Alamofire and passing in an array of dictionary values as the Parameters arg. Notice the 'User' key which contains a dictionary of values.

    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)
            }
        })

Right at the point where you are adding items to the dictionary, is where you can check for nil values and avoid adding as needed, thus making it dynamic.

Upvotes: 0

Syed Qamar Abbas
Syed Qamar Abbas

Reputation: 3677

If your web API demands the post data to send in JSON format then below written method is a way to do this.

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

    }
}

Upvotes: 0

Nirav D
Nirav D

Reputation: 72460

You just need to make Array of dictionary(user) as of currently you are setting user's value as Dictionary instead of Array.

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

}

Upvotes: 2

Related Questions