数组内的JSON数组 [英] JSON array inside of an array
问题描述
我正在寻找访问位于另一个数组内的JSON数组内的字符串.我正在使用JSONDecoder访问JSON API.在尝试使用JSON数组时过去使用的各种方法时,我收到错误消息.
I am looking to access a string that is located inside of a JSON array that is located inside of another array. I am accessing the JSON API using JSONDecoder. I am receiving errors when trying the various methods that I have used in the past when using JSON arrays.
这是代码:
var country = [Results]()
struct Rating: Codable {
let results: [Results]
}
struct Results: Codable {
let iso_3166_1: String
let release_dates: [Release_Dates]
}
struct Release_Dates: Codable {
let certification: String
}
func loadRating() {
let id = filmId
let apiKey = ""
let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)/release_dates?api_key=\(apiKey)")
let request = URLRequest(
url: url! as URL,
cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
timeoutInterval: 10 )
let session = URLSession (
configuration: URLSessionConfiguration.default,
delegate: nil,
delegateQueue: OperationQueue.main
)
let task = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
do { let rates = try! JSONDecoder().decode(Rating.self, from: data)
self.country = rates.results
let us = self.country.filter({ $0.iso_3166_1.contains("US") })
print(us)
}
}
})
task.resume()
}
us
打印到控制台
[Film.DetailsView.Results(iso_3166_1: "US", release_dates: [Film.DetailsView.Release_Dates(certification: "PG-13")])]
我正在尝试访问certification
字符串.
I am trying to access the certification
string.
用于实现此目的的正确方法是什么?
What would be the correct method used to achieve this?
推荐答案
us
是Results
的数组.
要获得第一个认证,请使用此:
To get the first certification use this:
print(us.first!.release_dates.first!. certification)
为简洁起见,我被迫解开包装,您应该使用可选的装订或保护声明正确地进行包装.
I am force unwrapping for brevity, you should properly do it with optional binding or the guard statement.
这篇关于数组内的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!