在我的项目中,我需要从网络获取 JSON 数据。同时,我会将其转换为 String
并将其存储在我的核心数据中。
假设我从网络获取此 JSON 数据。
我只需要帮助即可从 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 键是:platform
、favorite
和 language
你可以改变它们。 (请注意大小写)
关于json - Swift:获取 JSON 数据并在本地更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33434858/