我正在嘗試從 GitHub API 解碼 JSON 格式。api 的 url 是正確的,它回傳所有值,但 JSONdecoder 無法讀取它們。請幫忙,我做錯了什么?我之前已經為github api做過JSONDecoder,但我只需要用戶名和倉庫串列,但現在我需要有關特定倉庫的詳細資訊
有我的 func 解碼 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
}
有我的結構:
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
}
有從 GitHub API 回傳的 JSON 格式:https : //api.github.com/repos/allegro/typescript-strict-plugin
請告訴我我做錯了什么:)
uj5u.com熱心網友回復:
您的代碼對我來說效果很好,MoreInfo已根據需要進行解碼。使用 macos 12.2 Beta、Xcode 13.2,針對 ios 15 和 macCatalyst 12。在真實設備上進行了測驗。
正如@Larme 提到的,您當然需要處理異步函式。試試這個方法:
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)")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407086.html
標籤:
