![](/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.