【发布时间】:2018-06-23 19:31:36
【问题描述】:
我已将 JSON 值解码为对象。该对象看起来像预期的那样,但是当我尝试访问它的属性时。
let jsonData = try JSONSerialization.data(withJSONObject: JSON, options: [])
let decoder = JSONDecoder()
let doctor = try! decoder.decode(Doctor.self, from: jsonData)
let txt = "\(doctor.title). \(doctor.firstName) \(doctor.lastName)" // Runtime crash: (Thread 1: EXC_BAD_ACCESS (code=1, address=0x40))
运行时崩溃:(线程 1:EXC_BAD_ACCESS(代码=1,地址=0x40))
班级人员:
import UIKit
class Person: Codable {
let firstName: String
let lastName: String
let imageURL: URL
private enum CodingKeys: String, CodingKey {
case firstName
case lastName
case imageURL = "profileImgPath"
}
init(firstName: String, lastName: String, imageURL:URL) {
self.firstName = firstName
self.lastName = lastName
self.imageURL = imageURL
}
}
班主任:
import UIKit
class Doctor: Person {
var title: String
private enum CodingKeys: String, CodingKey {
case title
}
init(firstName: String, lastName: String, imageURL:URL, title: String) {
self.title = title
super.init(firstName: firstName, lastName: lastName, imageURL: imageURL)
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.title = try values.decode(String.self, forKey: .title)
try super.init(from: decoder)
}
}
【问题讨论】:
-
是
firstName和lastName在Doctor中的计算属性吗?你能显示Doctor类吗? -
我猜如果您不使用
try!并实际捕获异常,您可能会获得更多详细信息,您是否在Doctor 上实现了Codable? -
Doctor是Person的子类吗? -
@Kamran 我已经更新了问题
-
我认为它需要在 Person 类中使用
init(from decoder:)方法。编辑:我看到卡姆兰在他们的回答中做到了。
标签: ios swift nsjsonserialization