Answer the question
In order to leave comments, you need to log in
How to process JSON in Swift 3?
Hello. For a very long time I figured out how to process the JSON result of a request to the server using Alamofire.
I return Json in which there are internal json lines.
In array view, my JSON is:
var myArray = ["People0" : ["id": "1", "Name": "Alex"], "People1" : ["id": "2", "Name" : "Serg"]] etc.
I'm just learning Swift and working with JSON seemed incredibly difficult to me in it. The only working way for me looks like this:
let parameters: Parameters = ["parametr1": "1", "parametr2": "2", "parametr3": "3"]
Alamofire.request("http://link.php", method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success:
if let objJson = response.result.value as! NSDictionary? {
//for element in objJson {
for index in 0...(objJson.count)-1 {
let data = objJson["People" + String(index)] as! String
let dataNS = data.data(using: .utf8)
do {
let cont = try JSONSerialization.jsonObject(with: dataNS!, options: []) as? [String: Any]
let contData = cont as! [String:String]
self.names.append(String((index + 1)) + ". " + contData["Name"]!)
self.ids.append(Int(contData["id"]!)!)
} catch {
}
}
self.tableView.reloadData()
}
case .failure( _):
var errorString = "NULL"
if let data = response.data {
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String: String] {
errorString = json["error"]!
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Include a lib for parsing JSON, for example, one , two , three .
case .success:
let json = JSON(response.result.value)
let username: String? = json["People0"]["Name"].string
// ...
case .success:
let json = JSON(response.result.value)
let nestedJson = JSON(parseJSON: json["People0"].string ?? "{}")
let username: String? = nestedJson["Name"].string
// ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question