You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Swift 4解码特定JSON时遇到问题求助

解决Swift 4 JSON解码失败的问题

我一眼就看出问题所在啦——你当前的解码逻辑和JSON的结构完全不匹配!

先拆解下你的JSON结构:它的顶层是一个对象,包含三个核心键:Items(对应Animal数组)、Count和ScannedCount。但你直接尝试把整个JSON解码成[Animal].self(数组类型),解码器找不到对应的结构,自然会失败。

具体解决步骤:

  1. 创建顶层响应结构体
    先定义一个和JSON顶层结构完全匹配的结构体,用来包裹所有数据:

    struct AnimalResponse: Codable {
        let items: [Animal]
        let count: Int
        let scannedCount: Int
        
        // 用CodingKeys映射JSON的首字母大写键到Swift的小驼峰属性
        enum CodingKeys: String, CodingKey {
            case items = "Items"
            case count = "Count"
            case scannedCount = "ScannedCount"
        }
    }
    
  2. 优化Animal结构体(可选但推荐)
    你的JSON里id的值是1525680450507,这个数值超过了32位Int的最大值(2^31-1)。虽然64位系统下Swift的Int是64位能容纳,但为了全平台兼容性,建议把id的类型改成Int64:

    struct Animal: Codable {
        var id: Int64
        var animal: String
        var type: String
        var diet: [String]
    }
    
  3. 修改解码代码
    现在解码顶层的AnimalResponse,再从中取出目标Animal数组:

    let decoder = JSONDecoder()
    do {
        let response = try decoder.decode(AnimalResponse.self, from: data)
        let animals = response.items
        // 这里就可以正常使用animals数组啦
        print("解码成功:\(animals)")
    } catch {
        print("解码失败原因:\(error.localizedDescription)")
    }
    

偷懒小技巧:

如果不想手动写CodingKeys,可以设置解码器的键解码策略,自动把首字母大写的JSON键转换成小驼峰的Swift属性:

decoder.keyDecodingStrategy = .convertFromCapitalized

这样AnimalResponse里的items会自动匹配JSON的Items,count匹配Count,省去写CodingKeys的麻烦~

内容的提问来源于stack exchange,提问作者Jumpman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:11:54