Alamofire:使用字典数组发送JSON [英] Alamofire: Send JSON with Array of Dictionaries
问题描述
我有一个类似JSON的数据结构:
I have a data structure that looks like this in JSON:
[{
"value": "1",
"optionId": "be69fa23-6eca-4e1b-8c78-c01daaa43c88"
}, {
"value": "0",
"optionId": "f75da6a9-a34c-4ff6-8070-0d27792073df"
}]
基本上它是一个数组的字典。我宁愿使用默认的Alamofire方法,也不想手动构建请求。有没有办法给Alamofire提供我的参数,其余的由Alamofire承担?
Basically it is an array of dictionaries. I would prefer to use the default Alamofire methods and would not like to build the request manually. Is there a way to give Alamofire my parameters and Alamofire does the rest?
如果我手动创建所有内容,则会从服务器收到错误消息,提示发送数据不会正确。
If I create everything by hand I get an error from the server that the send data would not be correct.
var parameters = [[String:AnyObject]]()
for votingOption in votingOptions{
let type = votingOption.votingHeaders.first?.type
let parameter = ["optionId":votingOption.optionID,
"value": votingOption.votingBoolValue
]
parameters.append(parameter)
}
let jsonData = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
let json = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments)
if let url = NSURL(string:"myprivateurl"){
let request = NSMutableURLRequest(URL: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = Method.POST.rawValue
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
AlamofireManager.Configured.request(request)
.responseJSON { response in
//Handle result
}
}
推荐答案
您可以执行以下操作:
You can do something like this:
Alamofire.request(.POST, urlPath, parameters: params).responseJSON{ request, response, data in
//YOUR_CODE
}
其中参数
是 [String:AnyObject]
,是的,Alamofire负责其余部分。
Where parameters
is [String:AnyObject]
and yes Alamofire takes care of the rest.
因为看起来像您正在使用管理员,您可以执行此操作
Since it looks like you are using a manager you can do this
YOUR_ALAMOFIRE_MANAGER.request(.POST, url, parameters: params).responseJSON{ request, response, JSON in
//enter code here
}
源代码:
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
编辑:
由于您的数据当前为 [[String:AnyObject]]
,因此您需要对其进行修改,使其形式为 [String:AnyObject]
。您可以通过执行 [ data:[[String:AnyObject]]]
的一种方式来实现。不过,您可能必须更改api端点。
Since your data is currently [[String:AnyObject]]
you will need to modify it so it is in the form [String:AnyObject]
. One way you could do this i by doing this ["data":[[String:AnyObject]]]
. You will probably have to change your api end point though.
这篇关于Alamofire:使用字典数组发送JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!