Kam*_*ran 1 ios swift codable encodable
最近我加入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
}
}
Run Code Online (Sandbox Code Playgroud)
这很有效,但有没有更好的方法来实现同样的目标?
使用此扩展将可编码对象转换为 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)
}
}
Run Code Online (Sandbox Code Playgroud)
我的建议是命名函数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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5092 次 |
| 最近记录: |