所以我遇到了Swift 3的問題。我向我的服務器發送了一個get調用,並且我得到了我期望的數據。但我不知道如何從jsonArray創建對象,以便我可以輕鬆訪問數據。Swift 3 - 無法弄清楚如何從jsonArray創建json對象
這是迄今爲止我FUNC:
func getAllRoles(refreshToken: String){
print("vi kører getAllRoles \(refreshToken)")
let urlPath = "http://keebintest-pagh.rhcloud.com/api/users/allroles/"
let url = NSURL(string: urlPath)
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as! URL)
request.addValue(refreshToken, forHTTPHeaderField: "refreshToken")
request.httpMethod = "GET"
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
print("Task completed \(data) and response is xxxx")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString!)")
// Her laver vi data om til en dictionary
// let s = (try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers)) as! String
// print("det virkede?")
// print(s)
// var json: Array<String>!
// do {
// json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Array
// } catch {
// print(error)
// }
//
// print("her er mit json \(json[0])")
})
task.resume()
}
這是我的控制檯日誌是這樣的:
Task completed Optional(56 bytes) and response is xxxx
responseString = [{"id":1,"roleName":"Admin"},{"id":2,"roleName":"User"}]
here is my json {
id = 2;
roleName = User;
}
所以,很顯然,我得到我的數據,這是一個數組,我可以訪問。不過,我不知道如何從數組中的每個人創建jsonObjects。有人可以幫忙嗎?
在此先感謝!
可能重複的[將一個JSON數組反序列化爲一個Swift數組對象](http://stackoverflow.com/questions/37149588/deserialize-a-json-array-to-a-swift - 對象的陣列) – shallowThought