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

使用Swift 4 Codable解析JSON遇错误:String不符合Decoder类型

嘿,我来帮你搞定这个Codable解析的坑!

首先得揪出你代码里的核心问题——你一开始的错误和后续Xcode修复出的新问题,根源都是误用了URL的初始化方法,而且还没真正用上Codable来解析数据。

错误原因拆解

  1. 最初的错误「Argument type string does not conform to expected type decoder」:
    你写了URL(from: "http://json-schema.org/example/geo.json"),但URL(from:)是Codable协议里的初始化方法,它需要的是Decoder实例,不是字符串!编译器以为你要实现Codable的解码逻辑,自然会报错字符串不符合Decoder类型。

  2. Xcode自动修复后的类型转换错误:
    Xcode可能错误地帮你把字符串强转成了Decoder类型,这显然行不通,因为String和Decoder完全是两个不相关的类型,所以会出现「Could not cast value of type 'Swift.String' to 'Swift.Decoder'」。

修正后的完整代码

我把你的代码重构了一下,既解决了URL的问题,又正确用上了Codable解析:

import UIKit

struct aURL : Codable {
    let title: String
    let aurl: String
    // 如果URLStyle是自定义类型,记得也要让它遵守Codable协议
    // let style: URLStyle
}

class SectionTableViewController: UITableViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let queue = DispatchQueue(label: "cool")
        queue.async {
            // 用正确的URL初始化方法:URL(string:)
            guard let targetURL = URL(string: "http://json-schema.org/example/geo.json") else {
                print("无效的URL地址")
                return
            }
            
            do {
                // 用try替代try?,避免吞掉错误信息
                let data = try Data(contentsOf: targetURL, options: [])
                
                // 真正用Codable解析数据
                let decoder = JSONDecoder()
                let parsedURL = try decoder.decode(aURL.self, from: data)
                
                // 回到主线程更新UI(比如给表格赋值)
                DispatchQueue.main.async {
                    print("解析成功:标题\(parsedURL.title),地址\(parsedURL.aurl)")
                    // 这里可以添加更新表格UI的代码
                }
            } catch let error {
                print("出错了:\(error.localizedDescription)")
            }
        }
    }
}

关键改动说明

  • 替换URL初始化方法:把URL(from:)改成URL(string:),这才是通过字符串创建URL实例的正确方式。
  • 正确使用Codable:用JSONDecoder直接把Data解析成你定义的aURL结构体,这才是Swift 4+ Codable特性的正确打开方式,比JSONSerialization简洁多了。
  • 错误处理优化:去掉外层无效的do-catch,把错误捕获逻辑放到异步闭包内部,同时用try替代try?,这样能看到具体的错误信息,方便调试。
  • 可选补充:如果你的JSON字段名和结构体属性名不匹配(比如JSON里是url而不是aurl),可以添加CodingKeys来映射:
    enum CodingKeys: String, CodingKey {
        case title
        case aurl = "url"
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:46:16