在通过API调用解析JSON之后,我无法将解析的JSON转换为要显示在ViewController中的数据。我可以在控制台中打印JSON数据,但我不能仅从要显示的数据中获取“ word:..”的值。这是一个JSON对象的示例:
{
"metadata": {},
"results": [
{
"id": "eurhythmic",
"word": "eurhythmic"
}
]
}
我正在使用的结构如下:
// Struct RandomWords
struct StoreRandomWords: Codable {
let results: [Result]
}
struct Result: Codable {
let word: String
}
从API获取数据的代码:
func fetchRandomWord(completion: @escaping (StoreRandomWords?) -> Void) {
let language = "en"
let filters = "registers%3DRare%3Bdomains%3DArt?"
let limit = "limit=1"
let url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/wordlist/\(language)/\(filters)\(limit)")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
do {
let jsonData = try JSONDecoder().decode(StoreRandomWords.self, from: data)
print(jsonData)
} catch {
print(error)
}
} else {
print(error)
print(NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue)!)
}
}
task.resume()
}
以及我想在其中加载“单词”的ViewController中的代码:
// Do any additional setup after loading the view.
override func viewDidLoad() {
super.viewDidLoad()
// Fetch data for Daily Word.
ContextController.shared.fetchRandomWord( completion: { (storeRandomWord) in
if let storeRandomWord = storeRandomWord {
//
}
})
}
哪个在控制台上给了我这个输出:
StoreRandomWords(results: [GetContext.Result(word: "eurhythmic")])
我的目标是从字面上显示值字,此处是“律动性”。
(我是一个初学者,而不是英语母语人士,所以对于如何改进代码或问题的任何反馈都将有所帮助,并欢迎您。)
答案 0 :(得分:1)
您将必须循环数组或访问索引科学storeRandomWords.results是一个数组。
例如,打印第一个结果:
if let storeRandomWord = storeRandomWord {
print(storeRandomWord.results.first.word)
}