简体   繁体   中英

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. 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. The problem is I call JSON using this url:

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. 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. It's simpler to use 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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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