我正在尝试在 PHP 中构建一个对象数组,然后回显该数组以便在 Swift 中使用。当我对 JSON 对象执行 println
时,我可以在 Swift 中显示单个对象,但我需要回显许多对象。
class catRow{
public $id;
public $person;
public $item;
public $descr;
public $link;
public $price;
}
$prepare_string = "SELECT * FROM items ORDER BY person LIMIT 5";
$stmt = $dbh->prepare($prepare_string);
$stmt->execute();
while($row = $stmt->fetch()){
$catRow = new stdClass;
$catRow-> id = $row['id'];
$catRow-> person = $row['person'];
$catRow-> item = $row['item'];
$catRow-> descr = $row['descr'];
$catRow-> link = $row['link'];
$catRow-> price = $row['price'];
$allRows[] = $catRow;
}
echo json_encode($allRows);
然后在 Swift 方面我有(总结):
let catalogueRows: NSDIctionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
println(catalogueRows)
当我回显 $catRow
但我想回显数据库中该表中的每一行时,这会起作用。
最佳答案
allRows
是一个数组,而不是字典。所以你应该将 catalogueRows
转换为 NSArray
:
var error: NSError?
if let catalogueRows = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: &error) as? NSArray {
// successful, do something with `catalogueRows`
println(catalogueRows)
} else {
println("parse error: /(error)")
}
或者,也许更好,将其转换为一组 Swift 字典:
var error: NSError?
if let catalogueRows = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: &error) as? [[String: AnyObject]] {
// successful, do something with `catalogueRows`
println(catalogueRows)
} else {
println("parse error: /(error)")
}
请注意,在这两种情况下,我 (a) 捕获 error
对象; (b) 使用 if let
语法优雅地处理失败。
关于php - Echo PHP Swift NSDictionary 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27415293/