解决:
我能用这个来解决问题:
if let returnedData = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSString? {
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
let trimmedDataString = ((dataString.stringByReplacingOccurrencesOfString("YAHOO.Finance.SymbolSuggest.ssCallback", withString: "") as NSString).stringByReplacingOccurrencesOfString("(", withString: "") as NSString).stringByReplacingOccurrencesOfString(")", withString: "")
let dataFromDataString = trimmedDataString.dataUsingEncoding(NSUTF8StringEncoding)!
if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(dataFromDataString, options: .allZeros, error: nil) {
if let resultSet = jsonObject["ResultSet"] as! NSDictionary? {
println(resultSet)
}
}
}
原始问题:
我目前正在使用Yahoo!财务部门的YQL返回股票数据。我能够查询股票并成功返回所需信息,但前提是我知道股票的符号(AAPL,GOOG,FDX)。但是,我希望能够复制iOS'Stocks应用程序的搜索功能,它允许您在键入字符串时执行股票代码的实时搜索。
使用this网址检索信息时,我收到一条对我没用的JSON响应:
{"query":{"count":0,"created":"2015-06-01T23:49:49Z","lang":"en-us","results":null}}
但是,我已经能够从this URL找到我要查找的内容,但数据不是以我当前知道如何处理的JSON格式返回的:
YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"k","Result":[{"symbol":"K","name":"Kellogg Company","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KNDI","name":"Kandi Technologies Group, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"KO","name":"The Coca-Cola Company","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KMI","name":"Kinder Morgan, Inc.","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KMB","name":"Kimberly-Clark Corporation","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"GMCR","name":"Keurig Green Mountain, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"KORS","name":"Michael Kors Holdings Limited","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KLAC","name":"KLA-Tencor Corporation","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"KRFT","name":"Kraft Foods Group, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"^KLSE","name":"FTSE Bursa Malaysia KLCI","exch":"KLS","type":"I","exchDisp":"Kuala Lumpur Stock Exchange ","typeDisp":"Index"}]}})
我一整天都在寻找将这个返回的字符串转换为JSON对象的方法,以便在我的应用程序中使用。
由于它不是以JSON格式返回,我知道如何使用NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
进行解析,因此我一直在寻找从字符串创建JSON对象的方法。是否有一个我可以指出的方向,我只是错过了?
答案 0 :(得分:1)
试试这个:
if let returnedData = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSString? {
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(dataString, options: .allZeros, error: nil) {
if let resultSet = resultSet[yourDictionaryObject objectForKey:@"YAHOO.Finance.SymbolSuggest.ssCallback"]
//This should return a array of dictionary
}
}