![](/img/trans.png)
[英]Swift 4 Codable: Converting JSON return String to Int/Date/Float
[英]Converting Codable/Encodable to JSON object swift
最近我在一个项目中合并了Codable
并从符合Encodable
的类型中获取JSON
对象,我想出了这个扩展,
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
解码错误中抛出条件向下转换失败(类型不匹配)。
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)
guard let json = object as? [String: Any] else {
let context = DecodingError.Context(codingPath: [], debugDescription: "Deserialized object is not a dictionary")
throw DecodingError.typeMismatch(type(of: object), context)
}
return json
}
}
使用此扩展将可编码对象转换为 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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.