ios - Swift 无法将 NSString 转换为 JSON

标签 ios json swift swifty-json

我正在使用 WKUserScriptUIWebView 和服务器之间进行通信。此特定代码将允许用户搜索地理位置。我在函数中收到一条消息就好了

func userContentController(userContentController: WKUserContentController,
    didReceiveScriptMessage message: WKScriptMessage)

变量 message 有一个 AnyObject 主体。我想将该值转换为 JSONObject 以便我可以访问它的内容。这是 message.body:

{
    "status":"OK",
    "predictions":[
        {
            "description":"Dallas, TX, United States",
            "id":"fa589a36153613fc17b0ebaebbea7c1e31ca62f0",
            "matched_substrings":[{"length":6,"offset":0}],
            "place_id":"ChIJS5dFe_cZTIYRj2dH9qSb7Lk",
            "reference":"CkQxAAAAJNbPZRkdsyxuKT4FzFmgpBx9HWnZLNhxprRQB0zy62sHCXo3tkHfV_M5dK4Cabp2KL43nIKAAyrv_RI4qbvNfRIQ1dzEGuqywMIAlNg_1AKvoRoUQN32C2uNo4KzZ9j58lB-wjPpjJw",
            "terms":[
                {"offset":0,"value":"Dallas"},
                {"offset":8,"value":"TX"},
                {"offset":12,"value":"United States"}
            ],
        "types":["locality","political","geocode"]},
        {
            "description":"Dallas Athletic Club Drive, Dallas, TX, United States",
            "id":"37c4f8d416b9d3975ad57662eb022a0d410e8f76",
            "matched_substrings":[{"length":6,"offset":0}],
            "place_id":"EjVEYWxsYXMgQXRobGV0aWMgQ2x1YiBEcml2ZSwgRGFsbGFzLCBUWCwgVW5pdGVkIFN0YXRlcw",
            "reference":"CkQ5AAAArHSWkIVO6uTH4qE6LxRHshWAfgSnMfxXiBxqf_ZO3O-xQ8RIKKHA9QT7LKwf6Ic788Bzy_I2FpemvcQhE6o5ZRIQ5td4XsjIiyX6D6_dgI3YIxoURu_oROPuOguuorK3Tw11veN7XJI",
            "terms":[
                {"offset":0,"value":"Dallas Athletic Club Drive"},
                {"offset":28,"value":"Dallas"},
                {"offset":36,"value":"TX"},
                {"offset":40,"value":"United States"}
            ],
            "types":["route","geocode"]
        }
    ]
}

JSONObject 有一个状态,它让我知道结果是否有效或是否发生了错误。我正在使用 SwiftyJSON 创建和访问我的 JSON。我创建了 JSONObject:

let json = JSON(message.body as! NSString)

然后我尝试像这样访问状态键:

if let status = json["status"].string {
    print("status: \(status)")
}

但我无法访问打印语句。我注意到 NSDictionaryJSON 在将它们打印到控制台时有换行符,但我认为这不会有什么不同。有谁知道为什么我无法从 JSON 中检索状态变量?

最佳答案

您不能直接使用字符串初始化 SwiftyJSON 对象,您必须将此字符串转换为数据(如果是这种情况,或者使用您首先获得的数据)。

假设 message.body 是一个字符串:

if let dataFromString = message.body.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
    let json = JSON(data: dataFromString)
    if let status = json["status"].string {
        print("status: \(status)")
    }
}

关于ios - Swift 无法将 NSString 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318709/

相关文章:

ios - swift : How to add icon image and image background to the UItabBar in App delegate?

ios - 使用 DispatchGroup、DispatchQueue 和 DispatchSemaphore 按顺序执行带有 for 循环的 Swift 4 异步调用

iphone - 使用NSScanner查找短语的下一个匹配项

ios - 可以在后台运行并可以连接到设备的IOS应用程序

ios - 为什么我的 CAShapeLayer 不能正确地使用 UIView (w/gif) 设置动画?

MySQL - 在存在 GROUP BY 的情况下删除 JSON_ARRAYAGG 中的重复结果

javascript - 迭代node.js请求函数

ios - 如何使用 NSManagedObject 的子类?

regex - JSON 数字正则表达式

swift - ActionSheet 的工具栏问题