在我的Swift应用程序中,我正在下载存储在我服务器上的评论的JSON。 Web服务返回带有以下字段的JSON:
要使用该数据并在应用中正确解析,我创建了一个类SingleComment
:
class SingleComment: NSObject {
var id: String
let username: String
let photo_url: String
var descr: String
var updated_at: Date
var hashtag: [String]
init(id: String, username: String, photo_url: String, descr: String, updated_at: Date, hashtag: [String]) {
self.id = id
self.username = username
self.photo_url = photo_url
self.descr = descr
self.updated_at = updated_at
self.hashtag = hashtag
super.init()
}
class func fromJSON(_ json: JSON) -> SingleComment? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let id = json["_id"].string
let username = json["username"].string
let photo_url = json["photo_url"].string!
let descr = json["text_content"].string
let updated_at = json["updated_at"].string
let upd = dateFormatter.date(from: updated_at!)
let hashtag:[String] = json["hashtags"].arrayValue.map { $0.stringValue}
return SingleComment(id: id!, username: username!, photo_url: photo_url!, descr: descr!, updated_at: upd!, hashtag: hashtag!)
}
}
但问题是,有时json可能会错过某些字段,然后我收到的错误表明存在nil
个对象。我怎样才能防止它发生?目前我的应用程序崩溃,所以我认为我应该提供默认值或确保不需要这些字段。
这里最好的策略是什么?
答案 0 :(得分:0)
制作SingleComment
属性选项
class SingleComment: NSObject {
var id: String? // default they would be nil
let username: String?
let photo_url: String?
var descr: String?
var updated_at: Date?
var hashtag: [String]?
init(id: String? , username: String? , photo_url: String? , descr: String?, updated_at: Date?, hashtag: [String]?) {
self.id = id
self.username = username
self.photo_url = photo_url
self.descr = descr
self.updated_at = updated_at
self.hashtag = hashtag
super.init()
}
class func fromJSON(_ json: JSON) -> SingleComment {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let id = json["_id"].string
let username = json["username"].string
let photo_url = json["photo_url"].string
let descr = json["text_content"].string
let updated_at = json["updated_at"].string
let upd = dateFormatter.date(from: updated_at ?? "")
let hashtag:[String] = json["hashtags"].arrayValue.map { $0.stringValue}
return SingleComment(id: id, username: username, photo_url: photo_url, descr: descr, updated_at: upd, hashtag: hashtag)
}
}
并且每当使用SingleComment
属性时。使用if let
构造来使用它。