Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save StewartLynch/3f96b538606e6a124c3b249a3c9f1463 to your computer and use it in GitHub Desktop.
Save StewartLynch/3f96b538606e6a124c3b249a3c9f1463 to your computer and use it in GitHub Desktop.
JSON Decoding for Saurav
struct NewsFeed: Decodable {
let kind: String
let data: OuterData
struct OuterData: Decodable {
let children: [Child]
}
struct Child: Decodable {
let data: InnerData
}
struct InnerData: Decodable {
let title: String
let url_overridden_by_dest: String
let thumbnail: String
}
}
func getJSON() {
guard let url = URL(string: "https://www.reddit.com/r/UpliftingNews/hot.json") else {
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print(error.localizedDescription)
return
}
guard let data = data else {
return
}
let decoder = JSONDecoder()
guard let newsFeed = try? decoder.decode(NewsFeed.self, from: data) else { return }
let children = newsFeed.data.children
print(children.count)
for child in children {
print("""
\(child.data.title)
\(child.data.url_overridden_by_dest)
\(child.data.thumbnail)
""")
}
}.resume()
}
getJSON()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment