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

Swift JSON单字段解析失败报错,求助排查问题

问题原因

你的输入JSON本质是一个包裹了JSON对象的字符串,而非直接的JSON对象。原始内容的外层引号与转义符表明,整个内容是一个字符串值,而非解码器期望的键值对字典结构,这就是触发typeMismatch报错的核心原因。

解决方法

需要分两步解码:先解析外层字符串获取内部JSON文本,再将内部文本解码为目标结构体:

let messageBody = "{\"action\":\"question-answered\",\"data\":{\"type\":\"agreement\",\"questionType\":{},\"answer\":{}}}"

do {
    // 第一步:解码外层字符串,得到内部JSON文本
    let outerData = Data(messageBody.utf8)
    let innerJsonString = try JSONDecoder().decode(String.self, from: outerData)
    
    // 第二步:将内部JSON文本转为Data,解码为目标结构体
    let innerData = Data(innerJsonString.utf8)
    let symptomCheckerResult = try JSONDecoder().decode(SymptomCheckerResult.self, from: innerData)
    
    print(symptomCheckerResult.action) // 输出 "question-answered"
} catch {
    print(error)
}
简化方案(可选)

若不想进行两次解码,也可通过JSONSerialization直接解析并提取目标字段:

let messageBody = "{\"action\":\"question-answered\",\"data\":{\"type\":\"agreement\",\"questionType\":{},\"answer\":{}}}"

do {
    let outerData = Data(messageBody.utf8)
    let innerJsonString = try JSONSerialization.jsonObject(with: outerData) as! String
    let innerData = Data(innerJsonString.utf8)
    let jsonObject = try JSONSerialization.jsonObject(with: innerData) as! [String: Any]
    
    if let action = jsonObject["action"] as? String {
        print(action) // 输出 "question-answered"
    }
} catch {
    print(error)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:05:05