使用Alamofire 4解析嵌套的JSON

时间:2017-04-14 19:52:48

标签: json swift alamofire wordpress-rest-api

所以我一整天都在尝试使用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

我的目标是简单地调用和打印标题之类的东西(btw还嵌套了更多?)。我试图让它只与slug一起工作,因为我没有像渲染的标题那样嵌套,所以我想我应该从最简单的部分开始,但我甚至不能设法让它工作。

提前致谢。

2 个答案:

答案 0 :(得分: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。您可以下载并使用它来更好地了解映射的执行方式。

答案 1 :(得分:2)

对于这类任务,我建议你使用SwiftyJSON。它将帮助您保持简单和干净。 e.g。

    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
        }
    })
相关问题