Search code examples
jsonswiftmalformed

Formatting malformed data for JSON use in Swift


The output from this query:

http://chartapi.finance.yahoo.com/instrument/1.1/AAPL/chartdata;type=close;range=1d/json/

gives data that gives an error for JSON handling with AFNetworking. I was abled to download the data as shown below, but now need to get the stock data - unix times and prices - into an array for graphing. I am new to coding so text parsing is an emerging skill.

Suggestions?

var session = NSURLSession.sharedSession()
var request = NSURLRequest(URL: NSURL(string: "http://chartapi.finance.yahoo.com/instrument/1.1/AAPL/chartdata;type=close;range=1d/json/"))

var task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
    if !error {
        var string = NSString(data: data, encoding: 0)
        NSLog("%@", string)
    }
    })

task.resume()

Solution

  • If you don't need to use the callback function, you could just strip the outer layer as Hot Licks recommended. You should subclass AFHTTPResponseSerializer to accomplish this.

    For full JSONP callback support, you may want to configure AFNetworking with CDLJSONPResponseSerializer rather than rewriting your own serializer from scratch.