Swift:获取JSON数据并在本地更新

时间:2015-10-30 11:24:00

标签: json swift swift2 nsurlsession nsjsonserialization

在我的项目中,我需要从网上获取JSON数据。同时,我将其转换为String并将其存储在我的核心数据中。

假设我从网上获取此JSON数据。

enter image description here

我只需要帮助即可从JSON获取数据并转换为String Array。对不起,我对Swift2很新,我只知道如何编码直到这里。

var url: NSURL = NSURL(string: jsonUrl)!
var request: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()

2 个答案:

答案 0 :(得分:0)

let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "url")!, completionHandler: { (data, response, error) -> Void in
    if error != nil {
        //do something with error
        return
    }

    do {
        if let data = data, jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [[String:AnyObject]] {

            for object in jsonData {
                var object = Object()
                if let platform = object["platform"] as? String {
                    object.platform = platform
                }
            }
        }
    } catch {
        //Handle error
    }
})
task.resume()

答案 1 :(得分:0)

在这里,您可以使用本地网络服务在我的机器上进行测试

let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/iOSServer/ios/helloworld/getJSONArray")!)
        request.HTTPMethod = "GET" // change it to post if you want

        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if let error = error {
                print(error)
            }
            if let data = data{
                do{
                    let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                    let resultArray = resultJSON as? NSArray
                    for jsonObjectString in resultArray!{
                        let platform = jsonObjectString["platform"]!
                        let favorite = jsonObjectString["favorite"]!
                        let language = jsonObjectString["language"]!
                        print("platform = \(platform!)")
                        print("favorite = \(favorite!)")
                        print("language = \(language!)")
                    }

                }catch _{
                    print("Received not-well-formatted JSON")
                }

            }
            if let response = response {
                let httpResponse = response as! NSHTTPURLResponse
                print("response code = \(httpResponse.statusCode)")
            }



        })
        task.resume()
    }

如您所见,在for循环中,我正在打印服务器中的值,您可以随心所欲地执行任何操作。

我认为JSON密钥是:platformfavoritelanguage 你可以改变它们。 (请注意资金和小写字母)