【发布时间】:2018-08-25 14:12:48
【问题描述】:
[
{
"userId": 1,
"id": 1,
"title": "xxxxx",
"body": "yyyyy"
},
{
我的 json 数据就是这样,我使用 alamofire 加载数据,使用 objectmapper 进行映射。
我为这样的映射创建了一个 swift 文件:
import Foundation
import ObjectMapper
class TrainSchedules: Mappable {
var mySchedules: [Schedules]
required init?(map: Map) {
mySchedules = []
}
func mapping(map: Map) {
mySchedules <- map["schedule"]
}
}
class Schedules: Mappable {
var userId: String
var id: String
var title: String
var body: String
required init?(map: Map) {
userId = ""
id = ""
title = ""
body = ""
}
func mapping(map: Map) {
userId <- map["userId"]
id <- map["id"]
title <- map["title"]
body <- map["body"]
}
}
我的视图控制器是这样的:
import Alamofire
import ObjectMapper
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "Landmark"
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
@IBOutlet weak var tableViewData: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableViewData.dataSource = self
tableViewData.delegate = self
let jsonDataUrl = "https://jsonplaceholder.typicode.com/posts"
Alamofire.request(jsonDataUrl).responseJSON { response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("Result: \(response.result)")
if let json = response.result.value {
print("JSON: \(json)")
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
}
}
我尝试将 json 数据打印到 TableView。数据来了,但是我无法将它添加到 tableview。我应该怎么做才能解决这个问题?
【问题讨论】:
标签: ios json swift alamofire objectmapper