使用 Alamofire 4 解析嵌套 JSON
Parsing nested JSON with Alamofire 4
所以我整天都在尝试使用 Alomofire 4 从我的 WordPress REST API 解析 JSON,我已经尝试了所有我能找到的与我的问题相关的 is/was我仍然无法解决我的问题。
目标只是从 API 发出请求并将其打印出来,从那里我可以管理但是因为 JSON 似乎嵌套了 arrays/dictionaries 我有很难弄清楚该用什么。
我的代码:
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 工作,因为我不像呈现的标题那样嵌套,所以我想我应该从最简单的部分开始,但我什至无法让它工作。
提前致谢。
APIreturns一个字典数组,其中每个字典代表一个 Post 类型 [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。您可以下载并试用它,以更好地了解映射的执行方式。
对于这种任务,我建议您使用 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
}
})
所以我整天都在尝试使用 Alomofire 4 从我的 WordPress REST API 解析 JSON,我已经尝试了所有我能找到的与我的问题相关的 is/was我仍然无法解决我的问题。
目标只是从 API 发出请求并将其打印出来,从那里我可以管理但是因为 JSON 似乎嵌套了 arrays/dictionaries 我有很难弄清楚该用什么。
我的代码:
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 工作,因为我不像呈现的标题那样嵌套,所以我想我应该从最简单的部分开始,但我什至无法让它工作。
提前致谢。
APIreturns一个字典数组,其中每个字典代表一个 Post 类型 [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。您可以下载并试用它,以更好地了解映射的执行方式。
对于这种任务,我建议您使用 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
}
})