【问题标题】:Cannot parse JSON in Swift. "Expected to decode Dictionary<String, Any> but found an array instead." [duplicate]无法在 Swift 中解析 JSON。 “应解码 Dictionary<String, Any>,但找到了一个数组。” [复制]
【发布时间】:2021-11-14 01:52:19
【问题描述】:

我尝试从 JSON 中检索数据。 在我的代码下面有结构:

    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?
}

这是我在 dataDictionary.json 中指定的 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"
}]

}]

请帮助我正确编写结构。

【问题讨论】:

  • 只是因为你的json是数组。您可以将 json 转换为字典,也可以使 result 接受数组。

标签: json swift


【解决方案1】:

您的 JSON 是一个数组,因此应该这样处理。

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)")
    }
}

只是一个挑剔,但如果你可以确定你的 JSON 字段是非空的,那么你可以将你的模型属性更改为非可选的:

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

struct Result: Codable {
    let phonetic: String
    let phonetics: [Phonetic]
    let word: String
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多