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

Swift JSON解析示例报错:jsonObject方法无匹配调用

Swift JSON解析错误修复

你遇到的错误是因为JSONSerialization.jsonObject(with:)方法的第一个参数需要Data类型,但你传入的是字符串类型。补上字符串转Data的步骤即可解决问题。

修正后的代码:

import Foundation
// Example JSON with object root:
let jsonString = "{\"someKey\": 42.0,\"anotherKey\": {\"someNestedKey\": true }}"
// 将字符串转换为Data类型
guard let data = jsonString.data(using: .utf8) else {
    fatalError("无法将字符串转换为Data")
}
let json = try? JSONSerialization.jsonObject(with: data, options: [])

错误原因说明

原错误提示的中文翻译如下:

error: MyPlayground.playground:5:35: error: 调用类方法 'jsonObject' 时没有完全匹配的项
let json = try? JSONSerialization.jsonObject(with: data, options: [])
^

Foundation.JSONSerialization:7:21: note: 候选方法期望参数#1为'Data'类型(传入的是'String')
open class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
^

Foundation.JSONSerialization:13:21: note: 候选方法期望参数#1为'InputStream'类型(传入的是'String')
open class func jsonObject(with stream: InputStream, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
^

JSONSerialization的jsonObject(with:)方法仅支持Data或InputStream类型的输入,因此必须先将JSON字符串转换为Data实例才能正常调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:42:15