好的,我正在下类Implementing a custom Decoder in Swift 4然后解析器在 XML 中查找这些键:
struct RSSChannel: Codable {
var title: String
var pubDate: Date
var link: URL
var description: String
var items: [RSSItem]
enum CodingKeys: String, CodingKey {
case title, pubDate, link, description
case items = "item"
}
}'
(我没有写这个,这是 GitHub 所以我在这里挣扎)-
我需要知道如何在提要中不存在键(即发布日期)时阻止解析器出错。在 XMLDecoder 类中,有所有这些解码器:
public func decode(_ type: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try self.unbox(self.storage.topContainer, as: UInt.self)!
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try self.unbox(self.storage.topContainer, as: UInt8.self)!
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try self.unbox(self.storage.topContainer, as: UInt16.self)!
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try self.unbox(self.storage.topContainer, as: UInt32.self)!
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try self.unbox(self.storage.topContainer, as: UInt64.self)!
}
public func decode(_ type: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try self.unbox(self.storage.topContainer, as: Float.self)!
}
public func decode(_ type: Double.Type) throws -> Double {
try expectNonNull(Double.self)
实际上是:
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = self.container[key.stringValue] else {
print("SKYaw")
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
一堆这样的。当它说“No key associated with Key”/抛出错误时,有没有人遇到问题?我怎样才能使用这个库解决这个问题?
最佳答案
在 XMLParsing 库中,如果数据中可能不存在该属性,则需要将该属性设为可选。
如果 JSON 中不存在该值,这类似于您在 Apple 的 JSONDecoder 中发现的行为。
在您的示例中,您提到 pubDate
可能不存在于您的 XML 中,因此更新后的 channel 结构将如下所示:
struct RSSChannel: Codable {
var title: String
var pubDate: Date?
var link: URL
var description: String
var items: [RSSItem]
enum CodingKeys: String, CodingKey {
case title, pubDate, link, description
case items = "item"
}
}
因此,如果 pubDate
确实存在于您的 XML 中,那么该属性中就会有一个日期。在 XML 中不存在该键的情况下,pubDate
的值将为 nil
。
您可以在结构中将任意数量的属性设为可选,它们都将遵循此模式。
关于ios - 自定义 XML 解析器 - 当某些键不存在时该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50729181/