如何将 JSON 代码解析为 Swift 3 Table View 数据? [英] How to parse JSON code to Swift 3 Table View data?
问题描述
我正在使用 swift 3 和 MySQL 和 PHP 作为数据库创建一个 ios 应用程序.我想将数据从数据库输出到 tableview,但我一直有错误:Error Domain=NSCocoaErrorDomain Code=3840JSON 文本没有以数组或对象开头,并且没有设置允许片段的选项."我尝试检查PHP中的JSON编码,没问题.
I am creating an ios application using swift 3 and MySQL and PHP as database. I wanted to output the data from database to a tableview but i kept having an error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." I tried to check the JSON encoding in PHP, and it was ok.
这是我的快速代码:
class Roster: UITableViewController {
@IBOutlet weak var rosterbar: UITabBarItem!
var class_id = String()
var values: Array! = []
override func viewDidLoad() {
}
func SelectClassName(){
let request = NSMutableURLRequest(url: NSURL(string: "http://localhost/classdbfiles/SelectClass.php")! as URL)
request.httpMethod = "POST"
let postString = "class_id=\(Home.ClassVariables.class_id)"
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
}
print("response=\(response!)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("reponseString = \(responseString!)")
}
task.resume()
}
func get() {
guard let url = URL(string: "http://localhost/classdbfiles/SelectClass.php") else { return }
do {
let data = try Data(contentsOf: url)
let deserializedValues = try JSONSerialization.jsonObject(with: data)
guard let arrayOfDictionaryValues = deserializedValues as? [[String:String]] else { return }
values = arrayOfDictionaryValues
} catch {
//You should separate the different catch blocks to handle the different types of errors that occur
print("There was an error:\(error)")
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SpecialCell
let maindata = values[indexPath.row] as! [String:AnyObject]
cell.studentname.text = maindata["lastname"] as? String
return cell
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
SelectClassName()
get()
tableView.reloadData()
}
}
这是 PHP 文件:
if ($result = $mysqli->query("SELECT lastname from tbl_studentinfo where class_id='".$class_id."'")) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
推荐答案
假设您收到了以下形式的 JSON 文件:
Lets say you received a JSON file of the form:
{
"members": [
{"name": "Sarah"},
{"name": "David"},
{"name": "Michael"}
]
}
(注意大括号表示字典,方括号表示数组.)
(Note that curly brackets denote a dictionary, where as square brackets an array.)
在您的包中导入 JSON 文件.我叫我的 jsonfile.json
Import the JSON file in your bundle. I called mine jsonfile.json
然后使用以下方法解析 JSON 文件并获取成员,即包含成员名称的字典:
Then use the following method to parse the JSON file and get the members i.e. a dictionary that contains the member names:
func getMemeberDictionary()-> [[String: String]]{
guard let jsonFileURL = Bundle.main.url(forResource: "jsonfile", withExtension: "json") else {fatalError("Failed to get JSON file URl")}
var jsonData: Data!
var jsonDictionary: [String: AnyObject]!
//Getting JSON data from URL
do {
jsonData = try Data(contentsOf: jsonFileURL)
} catch let error as NSError{
print(error.debugDescription)
fatalError("Failed to initiate JSON data from URL!")
}
//getting top level JSON dictionary i.e. "members"
do {
jsonDictionary = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
} catch let error as NSError{
print(error.debugDescription)
fatalError("Failed to initiate top level JSON dictionary")
}
let memebers: [[String: String]] = jsonDictionary["members"] as! [[String: String]]
for person in memebers{
print(person["name"]!)
}
return memebers
}
这将返回一个 [[String: String]] 类型的数组,用它来设置你的表格视图.
This will return an array of type [[String: String]], use it to set up your table view.
此代码将所有成员导入到表视图中:
This code imports all members into a table view:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var members: [[String: String]]!
override func viewDidLoad() {
super.viewDidLoad()
members = getMemeberDictionary()
}
func getMemeberDictionary()-> [[String: String]]{
guard let jsonFileURL = Bundle.main.url(forResource: "jsonfile", withExtension: "json") else {fatalError("Failed to get JSON file URl")}
var jsonData: Data!
var jsonDictionary: [String: AnyObject]!
//Getting JSON data from URL
do {
jsonData = try Data(contentsOf: jsonFileURL)
} catch let error as NSError{
print(error.debugDescription)
fatalError("Failed to initiate JSON data from URL!")
}
//getting top level JSON dictionary i.e. "members"
do {
jsonDictionary = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
} catch let error as NSError{
print(error.debugDescription)
fatalError("Failed to initiate top level JSON dictionary")
}
let memebers: [[String: String]] = jsonDictionary["members"] as! [[String: String]]
for person in memebers{
print(person["name"]!)
}
return memebers
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return members.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = members[indexPath.row]["name"]
return cell
} else {
cell?.textLabel?.text = members[indexPath.row]["name"]
return cell!
}
}
}
结果:
如果您有任何其他问题,请随时问我.
Don't hesitate to ask me any further questions you may have.
这篇关于如何将 JSON 代码解析为 Swift 3 Table View 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!