Swift Can';t从我的.php文件中获取数组的json
我是Swift 3.0的新手,我正在尝试获取一个json,其中包含一些描述书籍的数组。这是我的代码:Swift Can';t从我的.php文件中获取数组的json,swift,Swift,我是Swift 3.0的新手,我正在尝试获取一个json,其中包含一些描述书籍的数组。这是我的代码: let myUrl = NSURL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php"); let request = NSMutableURLRequest(url:myUrl as! URL); request.httpMethod = "
let myUrl = NSURL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php");
let request = NSMutableURLRequest(url:myUrl as! URL);
request.httpMethod = "POST";
let postString = "name=\(libro)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
do {
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON: NSArray = json {
for index in 0...parseJSON.count-1 {
let libro = parseJSON[index] as! NSArray
print((libro[0] as AnyObject).value(forKey: "id"))
print((libro[0] as AnyObject).value(forKey: "id"))
}
}
} catch {
print("error=\(error)")
return
}
}
task.resume();
“libro”是一个字符串,我用POST方法传递给.php文件
以下是我编写的.php文件返回的json:
[{"id":"19","name":"CHIMICA","author":"MASSIMO CAFARDA","school":"PILATI","price":"20","status":"Come nuovo","isbn":"0987654321123","type":"IN VENDITA","idSeller":"2","nameSeller":"Stefano","surnameSeller":"Zanella"}]
我试图找到一些资料,但如果没有数组的名称,我无法获得json
有人能帮我吗?谢谢预期输出是什么?开始时,我想打印阵列的第一本书。当我学会如何打印时,我会继续。(在我的代码中,我已经写了两次“id”,但第二次应该是“name”)对不起,现在应该可以了。您使用Swift 3吗?然后尽量避免使用前缀为
NS
的所有类,比如NSArray
到Swift类型版本[Any]
等!NSArray那是一个Dict,不是数组。所以它应该是让libro=parseJSON[index]作为[String:Any]代码>然后打印(\(libro[“id”])代码>