[英]can not access the url inside of array , JSON response , using Alamofire & SwiftyJSON
[英]Alamofire response contain text before JSON content use it with SwiftyJSON
我正在使用Alamofire請求JSON對象,並使用SwiftyJSON訪問它。
我的請求的響應是這樣的:
// JSON webservice ...
[
{
"message":"Please connect"
}
]
如您所見,我需要刪除字符串“ // JSON webservice ...”,因為它實際上不是有效的JSON對象。 請注意,我使用的是.responseString,否則無法刪除字符串部分。
因此,為了刪除我正在做的字符串:
let jsonString = data?.stringByReplacingOccurrencesOfString("// JSON webservice ...", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
現在我可以使用String了:
var json = SwiftyJSON.JSON(jsonString!)
我可以打印json:
println(json)
但是無論我打印什么值
println(json[0]["message"].string)
是零。
我終於找到了解決方案:
我們將字符串轉換為NSData並嘗試序列化JSON對象:
let data = jsonString?.dataUsingEncoding(NSUTF8StringEncoding) let jsonData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray?
現在應該沒問題,嘗試打印JSON對象的值時一切正常
var json = SwiftyJSON.JSON(jsonData!) println(json[0]["message"])
它打印正確的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.