最近我将
Codable
合并到一个项目中,并从符合 JSON
的类型中获取 Encodable
对象,我想出了这个扩展,
extension Encodable {
/// Converting object to postable JSON
func toJSON(_ encoder: JSONEncoder = JSONEncoder()) -> [String: Any] {
guard let data = try? encoder.encode(self),
let object = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
let json = object as? [String: Any] else { return [:] }
return json
}
}
这很有效,但是还有更好的方法来实现同样的效果吗?
我的建议是将函数命名为
toDictionary
并将可能的错误交给调用者。有条件的向下转型失败(类型不匹配)会被抛出,并包含在 typeMismatch
De编码错误中。
extension Encodable {
/// Converting object to postable dictionary
func toDictionary(_ encoder: JSONEncoder = JSONEncoder()) throws -> [String: Any] {
let data = try encoder.encode(self)
let object = try JSONSerialization.jsonObject(with: data)
if let json = object as? [String: Any] { return json }
let context = DecodingError.Context(codingPath: [], debugDescription: "Deserialized object is not a dictionary")
throw DecodingError.typeMismatch(type(of: object), context)
}
}
使用此扩展将可编码对象转换为 JSON 字符串:
extension Encodable {
/// Converting object to postable JSON
func toJSON(_ encoder: JSONEncoder = JSONEncoder()) throws -> NSString {
let data = try encoder.encode(self)
let result = String(decoding: data, as: UTF8.self)
return NSString(string: result)
}
}