我正在尝试以下代码,但它引发了异常
content-div
它崩溃并显示以下错误
Error Domain = NSCocoaErrorDomain代码= 4865“没有与关联的值 键CodingKeys(stringValue:“ lastName”,intValue:nil)(“ lastName”)。” UserInfo = {NSDebugDescription =没有与键关联的值 CodingKeys(stringValue:“ lastName”,intValue:nil)(“ lastName”)。, NSCodingPath =()}
我知道JSON中缺少import Foundation
class SomeBaseClass: Codable {
let someInt: Int?
let someString: String?
init(someInt: Int,someString:String) {
self.someInt = someInt
self.someString = someString
}
init(someBaseClass: SomeBaseClass) {
self.someString = someBaseClass.someString
self.someInt = someBaseClass.someInt
}
}
class Person: SomeBaseClass {
let firstName: String?
let lastName: String?
init(firstName: String,lastName:String,someBaseClass: SomeBaseClass) {
self.firstName = firstName
self.lastName = lastName
super.init(someBaseClass: someBaseClass)
}
enum CodingKeys: String, CodingKey {
case firstName,lastName
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
try super.init(from: container.superDecoder())
}
}
let json = """
{
"firstName":"John",
"someInt":2
}
"""
let jsonData = json.data(using: .utf8)!
do {
let personObject = try JSONDecoder().decode(Person.self, from: jsonData)
dump(personObject)
} catch let error as NSError {
print(error)
}
,并且已将其标记为可选项,但它不能像它对结构的工作方式一样
有没有一种简单的方法可以做到这一点?
答案 0 :(得分:2)
您应该使用decodeIfPresent
作为可选属性
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decodeIfPresent(String.self, forKey: .firstName)
lastName = try container.decodeIfPresent(String.self, forKey: .lastName)
try super.init(from: decoder)
}
还请注意将super更改为避免另一个错误所需的更改。您也可以从
稍微更改捕获量} catch let error as NSError {
print(error)
}
简单地
} catch {
print(error)
}