如何在Swift 4中将JSON字典转换为字符串值

时间:2019-02-06 18:06:58

标签: json swift alamofire

我是Swift的新手,我开始使用PHP服务器开发Swift 4项目。 我使用Alamofire进行请求,并使用print()打印数据。这就是我得到的:

{"error":false,"n":"Raghad"}

但是当我想将其转换为String时,它返回""(空),并且  当我转换为布尔值时,它会正确返回值。

那么,我该如何解决?

let wJSON : JSON = JSON(response.result.value!)
print(wJSON["n"].stringValue)
print(wJSON["error"].boolValue)

2 个答案:

答案 0 :(得分:0)

使用Decodable的简单解决方案,为字典定义符合Decodable协议的Struct

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)
}

答案 1 :(得分:0)

我将responseString更改为responseJSON

Alamofire.request(Url !,方法:.post,参数:par).validate()。responseJSON {在if response.result.isSuccess中进行响应{让wJSON:JSON = JSON(response.result。值!)

而且有效