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

标签 json swift swift2 nsurlsession nsjsonserialization

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

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

enter image description here

我只需要帮助即可从 JSON 获取数据并将其转换为字符串数组。抱歉,我对 Swift2 还很陌生,直到这里我才知道如何编码。

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

最佳答案

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

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 你可以改变它们。 (请注意大小写)

关于json - Swift:获取 JSON 数据并在本地更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33434858/

相关文章:

json - "HelloWorld"是一个有效的 json 响应

javascript - 获取和使用 JSON 对象键名

ios - Swift - 如何查找数组中数组中项目的索引

ios - 在移动到下一个 Controller Swift iOS 之前错误隐藏键盘

swift - 如何快速连接字符串中的 "+"运算符

c# - System.Text.Json 从 API 调用反序列化嵌套对象 - 数据包装在父 JSON 属性中

python - 在 python 中使用\n 分隔的 JSON 发布请求

ios - 检查来自 Alamofire 和 Swift 的多个异步响应

swift - 如何在按下通知操作时运行 URL?

ios - 从 URL 将图像保存到库,重命名并使用 Swift 共享