I try to retrieve data from JSON. Below my code with structs:
private func ParseJSON() {
guard let path = Bundle.main.path(forResource: "dataDictionary", ofType: "json")
else {return}
let url = URL(fileURLWithPath: path)
var result: Result?
do {
let jsonData = try Data(contentsOf: url)
result = try JSONDecoder().decode(Result.self, from: jsonData)
if let result = result {
print(result)
} else {
print("Failed to parse")
}
return
}
catch {
print("Error:\(error)")
}
}
struct Phonetic: Codable {
let text: String?
let audio: String?
}
struct Result: Codable {
let phonetic : String?
let phonetics : [Phonetic]?
let word : String?
}
And here's my JSON-sample specified in dataDictionary.json:
[{
"word": "castle",
"phonetic": "ˈkɑːs(ə)l",
"phonetics": [{
"text": "ˈkɑːs(ə)l",
"audio": "//ssl.gstatic.com/dictionary/static/sounds/20200429/castle--1_gb_1.mp3"
}]
}]
Please help me to write my structs correctly.