I am trying to parse a large JSON String that I am retrieving from a URL. The JSON I am using to test is below:
let json = """
{
"feed": {
"title": "Harry Potter",
"test": "I dont want this value",
"results": [
{
"author": "JK Rowling",
"artworkURL": "A url",
"genres": [
{
"name": "Fantasy"
},
{
"name": "Scifi"
}
],
"name": "Goblet of Fire",
"releaseDate": "2000-07-08"
},
{
"author": "JK Rowling",
"artworkURL": "A url",
"genres": [
{
"name": "Fantasy"
},
{
"name": "Scifi"
}
],
"name": "Half Blood Prince",
"releaseDate": "2009-07-15"
}
]
}
}
""".data(using: .utf8)!
I have a couple data structs to place the data into:
struct Genre: Decodable {
let name: String
}
struct Book: Decodable {
let author: String
let artworkURL: URL
let genres: [Genre]
let name: String
let releaseDate: String
}
struct BookCollection {
let title: String
let books: [Book]
enum CodingKeys: String, CodingKey {
case feed
}
enum FeedKeys: String, CodingKey {
case title, results
}
enum ResultKeys: String, CodingKey {
case author, artworkURL, genres, name, releaseDate
}
enum GenreKeys: String, CodingKey {
case name
}
}
extension BookCollection: Decodable {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
let feed = try values.nestedContainer(keyedBy: FeedKeys.self,
forKey: .feed)
self.title = try feed.decode(String.self, forKey: .title)
self.books = try feed.decode([Track].self, forKey: .results)
}
}
I am then printing off the information like so:
do {
let response = try JSONDecoder().decode(BookCollection.self, from: json)
for book in response.books {
print(book.genres)
}
} catch {
print(error)
}
It is successful at printing off all of the information except for the genres. This gives me an array of genres, but I cannot do
book.genres.name
to access the name. I have to use:
book.genres[0]
and it gives me results for just the first index.
Is there a way I could perfect my JSON decoding in my BookCollection extension to then utilize book.genres.name?
Thank you
book.genres.nameshould return?FantasyandScifi.extension Book { var allGenres: [String] { return genres.map{$0.name} } }and useprint(book.allGenres)