Converting Dictionary to Json to pass parameters in Alamofire - ios

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": "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
}
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
}

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" : "abc#gmail.com"
],
[
"user_name" : "abc2",
"user_email" : "abc2#gmail.com"
]
]
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in
}

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

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.

Related

Problems in parse JSON array

I have this JSON:
{
"myData" : [
[
{
"text" : "lorem ipsum",
"id" : "myId"
}
]
]
}
And I want to get "text" and "id" values with SwiftyJSON.
My code:
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON { (response) in
switch response.result {
case .success(let value):
let json = JSON(value)
let id = json //json["myData"]["id"]... how get "id" ?
print(id)
}
It looks like you're accessing an array of arrays so you'll need to subscript out the elements you want like let id = json["myData"][0][0]["id"].

Request to Alamofire

I need to send a request to the server like this
[{
"Case":"add",
"Table":"user",
"Field":["Email","Password"],
"Value":["a","a"],
"Duplicate":["Email"],
"SecureEncrpt":"Password",
"SecureDecrpt":"Password"
}]
and I'm using alamofire for the network process, and im using request structure like this
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as AnyObject
let parameters = loginparas as! Parameters
How can I get exactly like that format?
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as [String:Any]
Alamofire.request( url , method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers ).responseJSON { response in
if response.result.isSuccess {
guard let json = response.result.value as? NSArray else { return }
for j in json {
let jsonValur = j as? [String:Any]
let case = jsonValue["Case"] as? String
...
...
...
}
}
}

Swift Alamofire migration parsing JSON

On migrating to recent versions am finding it hard to get and print the fields of name, age, and dob from JSON using Alamofire 4 parsing in Swift 3.
JSON FORMAT
"SetValues": {
"data":
[
{
"Name": yyyyy ,
"Age": 13,
"DOB": "2017-06-08",
}
{
"Name": xxxx ,
"Age": 33,
"DOB": "2015-06-08",
}
]
}
I tried
Alamofire.request(url!,
method: .post,
parameters: nil,
encoding: JSONEncoding.default,
headers: headers)
.responseJSON{ response in
let datamsg = jsonmsg?["SetValues"] as? [String : Any]
let dataset = datamsg?["data"] as? [String : Any]
let setValues = datamsg?["data"]
print (setValues[0]["Name"] as Any)
}
The problem is in this line
let dataset = datamsg?["data"] as? [String : Any]
as seen from the JSON response string it should be like below
let dataset = datamsg?["data"] as? [[String : Any]]
let name = dataset?[0]["Name"] as? String

swiftyjson getting string from json array

I am using alamofire and swiftyjson to get it. I need to get string "ubus_rpc_session", I tryed this way, but I get an array, I need to get string. Could you help me?
Alamofire.request(URL, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let token = json["result"].arrayValue.map({$0["ubus_rpc_session"].stringValue})
print(token)
{ "jsonrpc":"2.0",
"id":1,
"result":[
0,
{
"ubus_rpc_session":"07e111d317f7c701dc4dfde1b0d4862d",
"timeout":300,
"expires":300,
"acls":{
"access-group":{
"superuser":[
"read",
"write"
],
"unauthenticated":[
"read"
]
},
"ubus":{
"*":[
"*"
],
"session":[
"access",
"login"
]
},
"uci":{
"*":[
"read",
"write"
]
}
},
"data":{
"username":"root"
}
}
]
}
Try this
//Getting an array of string from a JSON Array(In their documents)
let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue})
if let tempArray = json["result"].arrayValue {
for item in tempArray {
print(item)
if let title = item["ubus_rpc_session"].string {
println(title)
}
}
}
Or check this
let value = tempArray[1].dictionaryObject!
print(value["ubus_rpc_session"]!)

Construction was too complex to be solved in reasonable time

I have problem with Swift 3, I am trying to send a request to a server and get JSON, but I get:
Construction was too complex to be solved in reasonable time.
I tried every way, but it doesn't worked.
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let parameters = [
"{\n",
" \"jsonrpc\": \"2.0\",\n",
" \"id\": \"1\",\n",
" \"method\": \"call\",\n",
" \"params\": [\n",
" \"0000000000000000\",\n",
" \"session\",\n",
" \"login\",\n",
" {\n",
" \"username\": \"" + userName + "\",\n",
" \"password\": \"" + password + "\"\n",
" }\n",
" ]\n",
"}"
]
let joiner = ""
let joinedStrings = parameters.joined(separator: joiner)
print("joinedStrings: \(joinedStrings)")
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1", method: .post, parameters: parameters).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Now I tryed to creat dic and convert to Json, but after that, I get problem on request there I declare my parameters. they say: use of unresolved identifier dictFromJSON
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let jsonObject: [String: Any] =
["jsonrpc" : 2.0,
"id": 1,
"method": "call",
"params": [ "00000000000000",
"session",
"login",
[ "username": userName,
"password": password]],
]
do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1/ubus", method: .post, parameters: dictFromJSON).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
UPDATED:
According to the document of Alamofire, (you can see here), you don't need to convert the parameters Dictionary to JSON.
For example,
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", parameters: parameters)
Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
OLD:
You should use Dictionay for the parameter actually.
Therefore, instead of declaring the parameter like you did, you should do like this:
let parameters = ["jsonrpc" : 2.0,
"id": 1,
"method": "call",
"params": [ "00000000000000",
"session",
"login",
[ "username": userName,
"password": password]],
]

Resources