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

为何JSONDecoder解码单个字符串报错、解码单个数字却正常?

Swift JSONDecoder解码字符串与整数的差异原因

当使用JSONDecoder解码字符串时抛出错误,但解码整数却能正常执行,具体现象如下:

异常案例:解码字符串

代码:

let data = "Sample String".data(using: .utf8)!

do {
    let decoder = JSONDecoder()
    let decoded = try decoder.decode(String.self, from: data)
    print(decoded)
} catch {
    print(error)
}

错误信息:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))

正常案例:解码整数

代码:

let data = "100".data(using: .utf8)!

do {
    let decoder = JSONDecoder()
    let decoded = try decoder.decode(Int.self, from: data)
    print(decoded)
} catch {
    print(error)
}

输出结果:

100

差异原因

核心原因是JSONDecoder严格遵循JSON语法规范,两者的合法性差异来自JSON本身的语法要求:

  • JSON中的字符串必须被双引号"包裹,裸写的Sample String不属于合法的JSON值,因此被判定为无效JSON,触发解码错误。如果要正常解码字符串,需要传入带双引号的原始数据,比如:
    let data = "\"Sample String\"".data(using: .utf8)!
    
  • JSON中的数字类型无需额外包裹,直接书写数字即可,100本身是合法的JSON数字值,因此可以被JSONDecoder正常解码为Int类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:40:20