首页 > 解决方案 > 为什么使用 JSONDecoder.decode 方法时没有调用 Decodable 的 init 方法?

问题描述

我正在尝试覆盖 JSONDecoder 解码数据的方式。

我尝试了以下方法:

struct Response : Decodable {
    init(from decoder: Decoder) throws {
        print("Hello")
    }
}

let result = try JSONDecoder().decode(Response.self, from: Data())

但是init(from:)不会被调用。基本上我希望在JSONDecoder将空数据解码为空Response对象时总是成功

标签: swiftcodable

解决方案


Data对象导致init方法抛出错误

给定的数据不是有效的 JSON。

在“Hello”被打印之前。


如果您想获得一个空Response对象(假设您不必调用任何指定的初始化程序)捕获dataCorrupted解码错误

struct Response : Decodable {}

var response : Response?
do {
    response = try JSONDecoder().decode(Response.self, from: Data())
} catch DecodingError.dataCorrupted(let context) where (context.underlyingError as NSError?)?.code == 3840 { // "The given data was not valid JSON."
    response = Response()
} catch { print(error) }

推荐阅读