-1

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.

  • 1
    It's just because your json is array. You can convert the json to just a dictionary or you can make `result` accept array. –  Nov 14 '21 at 01:59

1 Answers1

0

Your JSON is an array so it should be treated as such.

private func ParseJSON() {
    guard let path = Bundle.main.path(
        forResource: "dataDictionary", ofType: "json") else { fatalError() }

    let url = URL(fileURLWithPath: path)
    do {
        let jsonData = try Data(contentsOf: url)
        let result = try JSONDecoder().decode([Result].self, from: jsonData)
        print("Result: \(result)")
    } catch {
        print("Error:\(error)")
    }
}

Just a nitpick, but if you can be sure that your JSON fields are non-null then you can change your model properties to be non-optional:

struct Phonetic: Codable {
    let text: String
    let audio: String
}

struct Result: Codable {
    let phonetic: String
    let phonetics: [Phonetic]
    let word: String
}
Rob C
  • 4,877
  • 1
  • 11
  • 24