我的代码就是这个
import UIKit
import Alamofire
class ViewController: UIViewController {
var young = "https://jsonplaceholder.typicode.com/posts"
override func viewDidLoad() {
super.viewDidLoad()
callAlamo(url: young)
}
func callAlamo(url: String){
Alamofire.request(url).responseJSON { (response) in
let responseJSON = response.data
if responseJSON == nil{
print("response is empty")
}else{
print("Jon is \(responseJSON)")
self.parseJson(JSONData: responseJSON!)
}
}
}
func parseJson(JSONData: Data){
do{
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers)
for i in 0..<(readableJSON as AnyObject).count{
print(readableJSON[i] as String)
}
}catch{
print(error)
}
}
}
我需要这个Json中的每个数组元素。
答案 0 :(得分:3)
尝试使用以下代码:
Alamofire.request(url).responseJSON { (response) in
switch response.result {
case .success(let value) :
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value as! [String:AnyObject]!{
print("JSON: ",JSON)
}
case .failure(let encodingError):
completionHandler(APIResponse.init(status: "failure", response: nil, result:nil))
}
}
答案 1 :(得分:0)
使用responseJSON
处理程序时,JSON
已在JSONSerialization
内部解析Alamofire.request(url).responseJSON { response in
if let json = response.result.value {
print("Parsed JSON: \(json)")
// Now you can cast `json` to a Dictionary or Array
}
}
数据。您 NOT 想要再次尝试解析它,否则您将解析服务器的响应数据两次,这对性能非常不利。您需要做的就是:
FlipView.Loaded