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

如何解决Swift解析含字符串数组的JSON到Struct的解码错误?

问题解决:JSON解码类型不匹配的修复

错误原因

你的JSON数据中events数组存储的是字符串值(比如"Event1"),但定义的Event结构体要求的是包含name和description字段的字典对象,两者类型不匹配,导致解码失败。

解决方案

方案1:修改JSON结构适配现有结构体(若无法修改JSON则跳过)

把JSON中每个事件字符串改成对象格式,示例:

{
    "start": "2023-05-04T00:00:00Z",
    "end": "2023-06-05T18:00:00Z",
    "events": [
        {"name": "Event1", "description": "事件1的描述内容"}
    ]
}

方案2:修改Event结构体适配现有JSON(推荐)

自定义Event的解码逻辑,让它能把JSON中的字符串直接转换成Event实例:

struct Event: Codable, Identifiable {
    var id: String { name }
    var name: String
    var description: String
    
    // 自定义解码逻辑:将字符串解析为Event对象
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        // 读取JSON中的字符串作为事件名称
        let eventName = try container.decode(String.self)
        self.name = eventName
        // description可设为空字符串,或根据需求设置默认值
        self.description = ""
    }
    
    // 若需要将Event编码回JSON字符串,实现编码方法
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(name)
    }
}

struct EventDate: Codable {
    var start: String
    var end: String
    var events: [Event]
}

验证修改

修改完成后,使用原解码代码即可正常解析:

let allEventDates = Bundle.main.decode([EventDate].self, from: "event_dates.json")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:30:32