如何使用alamofire进行嵌套JSON数据解析? 实际上,我需要在表格视图中显示所有这些内容。
这是我的JSON API:
{
"status": "ok",
"posts": [
{
"id": 770,
"title": "Lorem Ipsum",
"content": "Reference site about Lorem Ipsum, giving information on its origins, as well as a random Lipsum generator.",
"date": "2019-02-19 06:43:33",
"categories": [
{
"id": 156,
"title": "News"
}
],
"attachments": [
{
"url": "https://website.com/wp-content/uploads/2019/02/image.jpg"
}
]
},
{22 items},
{22 items},
{22 items}
]
}
实际上,我需要在表格视图中显示所有这些信息。 -后-ID -后-标题 -后内容 - 发布日期 -职位-类别-ID -职位-类别-职务 -发布-附件-网址
这是我的代码。我不知道这是否正确。
import UIKit
import ObjectMapper
import AlamofireObjectMapper
import Alamofire
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var tableOut: UITableView!
var posts = [Post]()
let urlString = "https://website.com/api/get_recent_posts/"
//Model class for Post
class Post: Mappable {
var postContent: [Subpost]?
required init?(map: Map) {}
// Mappable
func mapping(map: Map) {
postContent <- map["posts"]
//print(postContent!) : its not working..... getting null value.
}
}
class Subpost:Mappable{
var title:String?
var slug:String?
required init?(map: Map) {}
func mapping(map: Map) {
title <- map["title"]
slug <- map["slug"]
//print(title!)
}
}
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(urlString, method: .get, encoding: JSONEncoding.default, headers: nil).responseObject { (response: DataResponse<Post>) in
//print("Response: \(response)")
print(response.result.value as Any)
if let blog = response.result.value{
//self.posts.append(contentsOf: blog)
self.tableOut.reloadData()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellObj = tableOut.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! TableViewCell
//cellObj.titleOut.text = posts[indexPath.row].title
// cellObj.slugOut.text = posts[indexPath.row].slug
return cellObj
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
}
TableViewCell.swift