Swift中的Alamofire:在可用的JSON字典中转换响应数据

编程入门 行业动态 更新时间:2024-10-17 20:32:22
本文介绍了Swift中的Alamofire:在可用的JSON字典中转换响应数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想处理一个JSON字符串,该字符串是使用 Alamofire 进行的HTTP调用作为数据返回的.

I would like to handle a JSON string that is returned as data from a HTTP call made using Alamofire.

此问题使用 SwiftyJSON .

但是我想稍微低一点",并了解如何将响应对象转换为字典.

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("aapiurl", parameters: nil) // Working with JSON Apple developer guide: // developer.apple/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字典中转换响应数据

本文发布于:2023-11-26 20:45:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   数据   Swift   Alamofire   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!