【问题标题】:Parsing nested JSON with Alamofire 4使用 Alamofire 4 解析嵌套的 JSON
【发布时间】:2017-09-11 02:44:51
【问题描述】:

所以我整天都在尝试使用 Alomofire 4 从我的 WordPress REST API 解析 JSON,我已经尝试了所有我能找到的与我的问题相关的东西,但我仍然无法解决我的问题。

目标只是从 API 发出请求并将其打印出来,我可以从那里管理,但由于 JSON 似乎有嵌套的数组/字典,我很难弄清楚要使用什么。

我的代码:

Alamofire.request(_newsURL).responseJSON { response in
        print(response.result)

        if let json = response.result.value as? [Any] {

            print("JSON: \(json)")
        }

        if let dict = response.result.value as? Dictionary<String, AnyObject>{

            print(response.result.value)

            if let slug = dict["slug"] as? String {

                self._newsSlug = slug
            }

            print("Hello News")
            print(self._newsURL)
            print(self._newsSlug)
        } else {
            print("Found Nothing")
        }
    }

API:http://www.wsvh.nl/wp-json/wp/v2/posts

我的目标是简单地调用并打印出诸如标题之类的东西(顺便说一句,它也嵌套了更多?)。我试图让它只用 slug 来工作,因为我不像渲染的标题那样嵌套,所以我想我应该从最简单的部分开始,但我什至无法让它工作。

提前致谢。

【问题讨论】:

    标签: json swift alamofire wordpress-rest-api


    【解决方案1】:

    对于此类任务,我建议您使用SwiftyJSON。它将帮助您保持简单和干净。 例如

        Alamofire.request(_newsURL).responseJSON(completionHandler: {
            response in
            if let value = response.result.value {
                let json = JSON(value) //Don't forget to import SwiftyJSON
                debugPrint(json)
                debugPrint(json[0]["slug"].stringValue) //print value of slug property
                debugPrint(json[0]["title"]["rendered"].stringValue) //print nested value of title
            }
        })
    

    【讨论】:

    • 哇,这真的很好用!我只是想知道,我该怎么做才能使标题成为 var 以便我可以使用它来操作 TableView?
    【解决方案2】:

    API 返回一个字典数组,其中每个字典代表[String: Any] 类型的帖子

    Alamofire.request(_newsURL).responseJSON { response in
      if let posts = response.result.value as? [[String: Any]] {
        posts.forEach { post in
          if let slug = post["slug"] as? String {
            print("Slug: \(slug)")
          }
          if let title = post["title"] as? [String: String] {
            print("Title: \(title["rendered"])")
          }
          if let categories = post["categories"] as? [Int] {
            print("Categories: \(categories)")
          }
          // You can retrieve as many field as you like as above...
        }
      }
    }
    

    我强烈建议您使用 ObjectMapper 这样的对象映射库,这样您就不必担心类型检查或强制转换了。

    只需创建一个名为Post的模型:

    import ObjectMapper
    
    class Post: Mappable, CustomStringConvertible {
    
      var title: String?
      var slug: String?
    
      var link: URL?
      var content: String?
    
      required init?(map: Map) {}
    
      func mapping(map: Map) {
        title <- map["title.rendered"]
        slug <- map["slug"]
    
        link <- (map["link"], URLTransform())
        content <- map["content.rendered"]
      }
    
      var description: String {
        return "Post <\(title ?? "No title")>"
      }
    }
    

    所以您可以按如下方式检索所有帖子:

    import AlamofireObjectMapper
    
    Alamofire.request("http://www.wsvh.nl/wp-json/wp/v2/posts")
      .responseArray { (response: DataResponse<[Post]>) in
    
        // This will give you the array of Post objects.
        print("Posts: \(response.result.value)")
    }
    

    我为你创建了一个example project。您可以下载并试用它,以更好地了解映射是如何执行的。

    【讨论】:

    • 终于打印出了请求!然而,我的最终目标是将它变成一个表格视图,所以我需要将 Title 设为 var,以便我可以使用它来操作文本。但是尝试将 Title 变成 var 会给我带来错误,因为它不是字符串。
    • 天哪!非常感谢 :D 这完全解决了我所有的问题,你让我摆脱了有史以来最头疼的问题。
    猜你喜欢
    • 2019-03-19
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2019-08-20
    相关资源
    最近更新 更多