简体   繁体   English

如何快速删除此JSON包装器?

[英]How can I remove this JSON wrapper in swift?

I'm currently making an app in swift that essentially functions as a virtual stock trading game. 我目前正在迅速开发一款基本上可以用作虚拟股票交易游戏的应用程序。 I was able to get most of the data I need using Yahoo's YQL service. 使用Yahoo的YQL服务,我可以获得所需的大部分数据。 A particular feature that I am working on now is a search function so that users can search for a stock ticker. 我现在正在使用的一个特殊功能是搜索功能,以便用户可以搜索股票行情记录。 I am making the app for IOS using Swift. 我正在使用Swift为IOS制作应用程序。 The problem is I call JSON using this url: 问题是我使用以下URL调用JSON:

http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=f&callback=YAHOO.Finance.SymbolSuggest.ssCallback http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=f&callback=YAHOO.Finance.SymbolSuggest.ssCallback

Which includes the extra text "YAHOO.Finance.SymbolSuggest.ssCallback(" and ")" around the JSON data which causes the code to be unable to parse the JSON data. 其中在JSON数据周围包含多余的文本“ YAHOO.Finance.SymbolSuggest.ssCallback(“和”)“,这会导致代码无法解析JSON数据。 How can I remove this? 我该如何删除? Thank you in advance. 先感谢您。

Here is my code: 这是我的代码:

    let callURL = NSURL(string: "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=f&callback=YAHOO.Finance.SymbolSuggest.ssCallback")

    var errorEncountered: Bool = false
    var downloadFinished: Bool = false
    var arrayOfStockResults: [[String]] = []

    let sharedSession = NSURLSession.sharedSession()
    let downloadTask: NSURLSessionDownloadTask =
    sharedSession.downloadTaskWithURL(callURL!, completionHandler: {
        (location: NSURL!, response: NSURLResponse!, error: NSError!)
        -> Void in

        if (error != nil) {
            errorEncountered = true
        }

        if (errorEncountered == false) {
            let dataObject = NSData(contentsOfURL: location)                     

           let stocksDictionary =
           NSJSONSerialization.JSONObjectWithData(dataObject!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

            println(stocksDictionary)

            if (error != nil) {
                errorEncountered = true
            }
            downloadFinished = true

I don't know why you're using downloadTaskWithURL and then using NSData's dataWithContentsOfURL to get the data. 我不知道为什么要使用downloadTaskWithURL然后使用NSData的dataWithContentsOfURL来获取数据。 It's simpler to use dataTaskWithURL. 使用dataTaskWithURL更简单。 The following code worked for me to download the data, convert it to a string, trim that string to remove unwanted text, convert that string back to an NSData object, and finally to get the dictionary. 以下代码对我有用,可以下载数据,将其转换为字符串,修剪该字符串以删除不需要的文本,将该字符串转换回NSData对象,最后获得字典。

var sharedSession: NSURLSession!

    override func viewDidLoad() {
        super.viewDidLoad()

        let callURL = NSURL(string: "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=f&callback=YAHOO.Finance.SymbolSuggest.ssCallback")

        var arrayOfStockResults: [[String]] = []

        sharedSession = NSURLSession.sharedSession()
        let downloadTask: NSURLSessionDataTask = sharedSession.dataTaskWithURL(callURL!, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                println(error)
            }else{
                var jsonError: NSError?
                var text: NSString = NSString(data: data, encoding: 4)!
                var range = text.rangeOfString("ssCallback")
                var subtext: NSString = text.substringFromIndex(range.location + range.length)
                var finalText = subtext.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "()")) // trim off the parentheses at both ends
                var trimmedData = finalText.dataUsingEncoding(4, allowLossyConversion: false)
                if let stocksDictionary = NSJSONSerialization.JSONObjectWithData(trimmedData!, options: .AllowFragments, error: &jsonError) as? NSDictionary {
                    println(stocksDictionary)
                }else{
                    println(jsonError)
                }
            }
        })
        downloadTask.resume()
    }

You could substring the request body 您可以将请求正文子字符串化

let startIndex = //enough to cut out yahoo prepend
let endIndex = //enough to cut off that ending paren

//assuming some data variable for request body
data.substringWithRange(Range<String.Index>(start: startIndex, end: endIndex))

then json-ify it! 然后json-ify它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM