json - 如何在swift 4中将JSON字典转换为字符串值
问题描述
我是 Swift 新手,我开始使用 PHP 服务器处理 Swift 4 项目。我使用 Alamofire 请求请求,并使用print()
. 这就是我得到的:
{"error":false,"n":"Raghad"}
但是当我想将它转换为字符串时,它会返回""
(空),当我转换为布尔值时,它会正确返回值。
那么,我该如何解决呢?
let wJSON : JSON = JSON(response.result.value!)
print(wJSON["n"].stringValue)
print(wJSON["error"].boolValue)
解决方案
使用简单的解决方案Decodable
,定义一个符合Decodable
字典协议的结构
struct Reply: Decodable {
let error: Bool
let n: String
}
let data = response.data
do {
let result = try JSONDecoder().decode(Reply.self, from: data)
print("\(result.n) \(result.error)")
} catch {
print(error)
}
推荐阅读
- mysql - Digital Ocean / Nginx / MySQL / MVC 部署
- python - 在detectron2中,如何在对象检测中仅在没有标签(类名)的图像上绘制边界?
- python - Python for循环csv并发
- python - 如何在 Jupyter 的 URL 中传递密码?
- typescript - Msgraph - 从 msgraph api 下载 .eml 作为 itemAttachment
- ios - 如何在不使用 GoogleMap API 的情况下表达最近的地铁站名称?(iOS,斯威夫特)
- javascript - 如何将文件路径作为命令行参数传递?
- python - attrs 如何欺骗调试器进入自动生成的代码?
- javascript - React Stripe - 将状态映射到条带注入组件上的道具?
- amazon-web-services - Terraform AWS CloudTrail 配置失败