Swift无法将NSString转换为JSON

时间:2015-08-31 19:37:59

标签: ios json swift swifty-json

我使用WKUserScript进行UIWebView与服务器之间的通信。此特定代码将允许用户搜索地理位置。我在函数

中收到了一条消息
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

中检索状态变量

1 个答案:

答案 0 :(得分:1)

您不能直接使用字符串初始化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)")
    }
}