I am trying to decode a JSON format from GitHub API. The URL to the API is correct, it returns all values, but JSONdecoder
can't read them. Please help, what am I doing wrong?
I have already done JSONDecoder
for GitHub API before, but I only needed the username and repository list, but now I need details about a specific repository
There is my func to decode JSON:
func getMoreInfo() -> MoreInfo {
var moreInfo = MoreInfo(name: "", moreInfoDescription: "", contributorsURL: "", stargazersCount: 0, language: "", forksCount: 0, license: License(key: "", name: ""), topics: [])
if let url = URL(string: "https://api.github.com/repos/allegro/typescript-strict-plugin"){
URLSession.shared.dataTask(with: url) { data, responde, error in
if let data = data {
do {
moreInfo = try JSONDecoder().decode(MoreInfo.self, from: data)
} catch let error {
print(error)
}
}
}.resume()
}
return moreInfo
}
There are my structs:
let name, moreInfoDescription: String
let contributorsURL: String
let stargazersCount: Int
let language: String
let forksCount: Int
let license: License
let topics: [String]
enum CodingKeys: String, CodingKey {
case name
case moreInfoDescription = "description"
case contributorsURL = "contributors_url"
case stargazersCount = "stargazers_count"
case language
case forksCount = "forks_count"
case license, topics
}
}
struct License: Codable {
let key: String
let name: String
}
There is the JSON format that gets returned from GitHub API: https://api.github.com/repos/allegro/typescript-strict-plugin
Please tell me what I am doing wrong :)
Your code works well for me, MoreInfo
is decoded as required.
Using macos 12.2 Beta, Xcode 13.2,
targets ios 15 and macCatalyst 12. Tested on real devices.
You of course need to deal with the asynchronous function, as @Larme mentioned. Try this approach:
func getMoreInfo(completion: @escaping(MoreInfo?) -> ()) {
if let url = URL(string: "https://api.github.com/repos/allegro/typescript-strict-plugin"){
URLSession.shared.dataTask(with: url) { data, responde, error in
if let data = data {
do {
let moreInfo = try JSONDecoder().decode(MoreInfo.self, from: data)
completion(moreInfo)
} catch let error {
print(error)
completion(nil) // todo deal with errors
}
}
}.resume()
}
}
and use it like this:
getMoreInfo() { info in
print("\n-------> info: \(info)")
}