Swift中的Alamofire:在可用的JSON字典中转换响应数据 [英] Alamofire in Swift: converting response data in usable JSON dictionary
问题描述
我想处理一个JSON字符串,该字符串是使用 Alamofire 进行的HTTP调用作为数据返回的.
I would like to handle a JSON string that is returned as data from a HTTP call made using Alamofire.
此问题使用但是我想稍微低一点",并了解如何将响应对象转换为字典.
However I wanted to go a little bit "lower level" and understand how to convert the response object into a dictionary.
推理是,感觉字典可能是访问响应中JSON值的简单方法(而不是必须经历将响应转换为JSON对象的过程).
Reasoning is that it feels that a dictionary may be a simple / easy way to access to the JSON values in the response (rather than having to go through the process of converting the response to a JSON object).
这是基于JSON对象和字典是同一件事(是吗?)的假设.
This is under the assumption that JSON objects and dictionaries are the same thing (are they?).
这是我编写的示例函数:
Here is the sample function that I wrote:
func question() -> Void{
let response : DataRequest = Alamofire.request("http://aapiurl", parameters: nil)
// Working with JSON Apple developer guide:
// https://developer.apple.com/swift/blog/?id=37
response.responseJSON { response in
if let JSON = response.result.value
{
print("JSON: \(JSON)") // Works!
let data = JSON as! NSMutableDictionary
// Casting fails
// Could not cast value of type '__NSCFArray' (0x19f952150) to 'NSMutableDictionary' (0x19f9523f8).
print("Data: \(data)")
}
}
}
JSON对象似乎是Any类型,并且没有以下答案中建议的任何方法.
The JSON object seems to be of type Any and does not have any of the methods that are suggested in the answers below.
我尝试将其转换为字典,并出现以下错误:
I have tried to convert it to a Dictionary and got the error below:
推荐答案
Alamofire的结果值类型为Any
,因为它通常是数组或字典.在Swift中,通常不应使用NS *类,而应使用本机swift类型,例如Array
和Dictionary
.
Alamofire has the result value of type Any
because it usually would be an array or a dictionary. In Swift you normally shouldn't use NS* classes, but rather native swift types such as Array
and Dictionary
.
您可以(应该)使用可选参数来查看返回的JSON对象:
You can (should) use optionals to look into the returned JSON object:
if let array = response.result.value as? [Any] {
print("Got an array with \(array.count) objects")
}
else if let dictionary = response.result.value as? [AnyHashable: Any] {
print("Got a dictionary: \(dictionary)")
}
...
根据您对后端的期望,可以将每种情况视为成功还是失败.
Depending on what you expect from your backend, you can treat each of the cases as a success or a failure.
这篇关于Swift中的Alamofire:在可用的JSON字典中转换响应数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!