首页 > 解决方案 > 如何在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)

标签: jsonswiftalamofire

解决方案


使用简单的解决方案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)
}

推荐阅读