我有一些实时股票价格数据的工作链接,我试图将其导入我的Swift应用程序。包含数据的HTML文件非常干净,除了它以" //"开头。在它列出适当的价格之前。我认为那些角色正在创造"无效角色" JSON序列化时出错。
这是我执行序列化的代码。它在"返回时崩溃(试试!JSONSerialization ...")行
// [ { "id": "33312" ,"t" : "T" ,"e" : "NYSE" ,"l" : "39.47" ,"l_fix" : "39.47" ,"l_cur" : "39.48" ,"s": "0" ,"ltt":"2:47PM EST" ,"lt" : "Nov 29, 2:47PM EST" ,"lt_dts" : "2016-11-29T14:47:29Z" ,"c" : "-0.07" ,"c_fix" : "-0.07" ,"cp" : "-0.16" ,"cp_fix" : "-0.16" ,"ccol" : "chr" ,"pcls_fix" : "39.54" } ]
这是所有返回的数据:
#
有没有办法去跳过"开头的两个角色,还是有另一种解决这个问题的方法,我不知道?谢谢!
答案 0 :(得分:0)
尝试删除像这样的“\”字符怎么样:
public class func query(statement: String) -> NSDictionary {
let prefix = ""
let query = "\(prefix)NASDAQ:\(statement)"
var data = String(describing: (contentsOfURL: NSURL(string: query)!, encoding: String.Encoding.utf8))
data = data.substring(from: data.characters.index(data.startIndex, offsetBy: 2))
let jsonData = data.data(using: String.Encoding.utf8)
let result = { _ -> NSDictionary in
if let data = jsonData {
let array = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
return array.count > 0 ? array[0] as? NSDictionary ?? NSDictionary() : NSDictionary()
}
return NSDictionary()
}()
return result
}
答案 1 :(得分:0)
首先,您尝试返回NSDictionary
,但您的数据是Array
词典:
let result = { _ -> NSDictionary in
使用以下代码也可以使用substring
切断前两个字符:
var test = "// [ { \"id\": \"33312\" ,\"t\" : \"T\" ,\"e\" : \"NYSE\" ,\"l\" : \"39.47\" ,\"l_fix\" : \"39.47\" ,\"l_cur\" : \"39.48\" ,\"s\": \"0\" ,\"ltt\":\"2:47PM EST\" ,\"lt\" : \"Nov 29, 2:47PM EST\" ,\"lt_dts\" : \"2016-11-29T14:47:29Z\" ,\"c\" : \"-0.07\" ,\"c_fix\" : \"-0.07\" ,\"cp\" : \"-0.16\" ,\"cp_fix\" : \"-0.16\" ,\"ccol\" : \"chr\" ,\"pcls_fix\" : \"39.54\" } ] "
let result = test.substring(from: test.characters.index(test.startIndex, offsetBy: 2))
let data = result.data(using: .utf8)
var array = [[String:Any]]()
do {
array = try JSONSerialization.jsonObject(with: data!, options: []) as! [[String: Any]]
} catch {
print(error)
}
print(array.first!)
结果:
["ltt": 2:47PM EST, "l_fix": 39.47, "lt_dts": 2016-11-29T14:47:29Z, "c_fix": -0.07, "lt": Nov 29, 2:47PM EST, "t": T, "pcls_fix": 39.54, "cp": -0.16, "ccol": chr, "id": 33312, "cp_fix": -0.16, "c": -0.07, "s": 0, "e": NYSE, "l": 39.47, "l_cur": 39.48]