Разбор вложенного JSON с AlamofireObjectMapper - PullRequest
0 голосов
/ 20 февраля 2019

Как мне выполнить анализ вложенных данных JSON с помощью alamofire?На самом деле мне нужно отобразить все это в виде таблицы.

  • post - id
  • post - tittle
  • post - content
  • post - date
  • post - category - id
  • post - категории - заголовок
  • post - вложения - url

Это мой 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}
       ]
    }

На самом деле мне нужноотобразить все это в виде таблицы.- post - id - post - tittle - post - контент - post - date - post - категории - id - post - категории - title - post - вложения - url

Это мой код.я не знаю, правильно ли это.

  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

  • @ IBOutlet слабый var slugOut: UILabel!
  • @ IBOutlet, слабая переменная titleOut: UILabel!
  • @ IBOutlet слабый var contentOut: UILabel!
  • @ IBOutlet слабый var imageOut: UIImageView!и т. д.
...