swift - 为什么使用 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
对象时总是成功
解决方案
空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) }
推荐阅读
- excel - 设置 Excel 文件的 MsoAutomationSecurity
- java-native-interface - 构建后 libstandalonelibwebviewchromium.so 中的方法名称更改
- java - Spring boot:java.lang.IllegalStateException:Bean 名称“edit”的 BindingResult 和普通目标对象都不能用作请求属性
- c# - MethodInfo.CreateDelegate 与异步任务返回类型
- reactjs - 为什么代码会触发“太多渲染”,为什么它会“未定义”?
- selenium - Jest + Selenium:在运行描述块内的所有测试之前和之后如何进行操作?
- java - 为什么我在IntelliJ中运行项目时maven使用旧版本的Vaadin插件?
- excel - 如何将一行中的字符串与excel中的另一个字符串匹配?
- kotlin - Kotlin 原生编译时间
- python - 是否可以在 Kivy 中使用多个 ScreenManager 小部件?