Swift中的远程JSON解析对我来说是新的,而且我花了数周时间试图解决这个问题。
我来自的JSON是这个人: http://www.odysseynewsmagazine.net/wp-json/wp/v2/posts?_embed
我正试图达到那个" source_url"对于每个帖子的图像,但它嵌套在" media_details"它嵌套在" wp:featuredmedia"它嵌套在" _embedded"我一直在犯错误。
我写的代码看起来像这样:
func parseData() {
fetchedSlug = []
//from odyssey site
let url = "http://www.odysseynewsmagazine.net/wp-json/wp/v2/posts?_embed"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
print("Error")
}
else {
do {
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
//Json objects to variables
for eachFetchedSlug in fetchedData {
let eachSlug = eachFetchedSlug as! [String: Any]
let slug = eachSlug["slug"] as! String
let link = eachSlug["link"] as! String
self.fetchedSlug.append(Slug(slug: slug, link: link))
}
self.slugTableView.reloadData()
}
catch {
print("Error2")
}
}
}
task.resume()
}
}//end of VC Class
class Slug {
//define variables
let slug: String?
let link: String?
init(slug: String?, link: String?) {
self.slug = slug
self.link = link
}
//creating dictionaries from Json objects
init(slugDictionary: [String : Any]) {
self.slug = slugDictionary["slug"] as? String
link = slugDictionary["link"] as? String
}
}
我还需要在"呈现"中找到的每个帖子的标题。在" title"。
所有这些信息都在tableView中的可重用自定义单元格中填充标签。我可以填充slug和链接标签,但不能填充任何嵌套信息。
在#34;嵌入"之前的下划线是什么?这就是我无法做到的原因吗?我可以让它消失吗?在我向他们展示正在运行的应用之前,我不允许下载插件或运行自定义脚本。
答案 0 :(得分:0)
安装更好的REST API精选图片插件
答案 1 :(得分:0)
请检查以下代码:
for eachFetchedSlug in fetchedData {
let eachSlug = eachFetchedSlug as! [String: Any]
let slug = eachSlug["slug"] as! String
let link = eachSlug["link"] as! String
self.fetchedSlug.append(Slug(slug: slug, link: link))
let title = eachSlug["title"] as! [String: Any]
let rendered = String(describing: title["rendered"])
print(rendered) // this is title
let embedded = eachSlug["_embedded"] as! [String: Any]
let wpfeaturedmedias = embedded["wp:featuredmedia"] as! [Any]
for wpfeaturedmedia in wpfeaturedmedias {
let featuredmedia = wpfeaturedmedia as! [String: Any]
let mediaDetails = featuredmedia["media_details"] as! [String: Any]
let mediaDetailsSize = mediaDetails["sizes"] as! [String: Any]
let mediaDetailsSizeThumbnail = mediaDetailsSize["thumbnail"] as! [String: Any] // getting only thumbnail. Based on you requirement change this to
let image = String(describing: mediaDetailsSizeThumbnail["source_url"])
print(image) // this is image
}
}
我添加了仅检索thumbnail
的代码。在sizes
中有很多类型(medium
,medium_large
...)。根据您的要求,更改值。
如果要检查选项,最好添加。因为那里有很多转换。如果它在任何转换中失败,它将崩溃。