【问题标题】:JSON Decoder Type Mismatch Error in SwiftSwift 中的 JSON 解码器类型不匹配错误
【发布时间】:2021-02-22 00:31:32
【问题描述】:

当我尝试解码 JSON 时出现错误:

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1972", intValue: 1972), CodingKeys(stringValue: "song_name", intValue: nil)], debugDescription: "预期解码字符串,但找到了一个数字。”,基础错误:无))

  1. JSON:
[
  {
    "song_id": 1373123,
    "song_name": "신라의 달밤",
    "artist": "현인",
    "album": "현인",
    "Like_count": 100,
    "Lyric": "아~ 신라의 밤이여\n불국사의 종소리 들리어 온다\n지나가는 나그네야 걸음을 멈추어라\n고요한 달빛 어린 금오산 기슭에서\n노래를 불러보자 신라의 밤 노래를\n\n아~ 신라의 밤이여\n아름다운 궁녀들 그리워라\n대궐 뒤에 숲 속에서 사랑을 맺었던가\n님들의 치맛소리 귓속에 들으면서\n노래를 불러보자 신라의 밤 노래를",
    "cover_url": "https://image.bugsm.co.kr/album/images/200/1134/113497.jpg?version=20170925032718.0"
  },
...
  1. Swift 代码
        let decoder = JSONDecoder()
        do {
            self.songs = try decoder.decode([Song].self, from: asset.data)
        } catch {
            print(error)
        }
  1. 型号
struct Song: Codable {
//    var id: Int
    var title: String
    var artist: String
//    var album: String
//    var like: Int
//    var lylic: String
//    var coverURL: String
    
    enum CodingKeys: String, CodingKey {
//        case id = "song_id"
        case title = "song_name"
        case artist = "artist"
//        case album = "album"
//        case like = "Like_count"
//        case lylic = "Lyric"
//        case coverURL = "cover_url"
    }
}

【问题讨论】:

  • 一切都适用于您发布的 JSON。该错误意味着song_name 是一个数字而不是字符串。也许,在真正的 JSON 中,有时会有一个 song_name 是数字的对象?

标签: ios json swift


【解决方案1】:

错误非常明显:在数组的第 1973 项(索引 1972)中,键 song_name 的值是一个数字。例如,您必须添加自定义初始化程序来解决问题

struct Song: Decodable {
    let id : Int
    let title : String
    // ... other struct members

    enum CodingKeys: String, CodingKey {
        case id = "song_id"
        case title = "song_name"
    // ... other CodingKeys
    }        

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(Int.self, forKey: .id)
        do {
            self.title = try container.decode(String.self, forKey: .title)
        } catch {
            let numberName = try container.decode(Int.self, forKey: .title)
            self.title = String(numberName)
        }
        // other lines to initialize the other struct members
    }
}

如果错误仍然存​​在,数字也可能是Double 或Bool。

【讨论】:

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