JSONEncoder
在 Swift 中還是非常常用的,最近項目中有需要將APP數據轉換爲JSON格式之後,再發送給服務器的需求,測試過程中,然後報瞭如下錯誤:
invalidValue(Optional(1),
Swift.EncodingError.Context(codingPath: [], debugDescription: "Top-level Optional<Int> encoded as number JSON fragment.", underlyingError: nil))
移除業務邏輯的話,代碼大概長這樣:
class ViewController: UIViewController {
struct User: Codable {
var name: String
var age: Int
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .red
// Do any additional setup after loading the view.
sendData(1, res: nil)
sendData(User(name: "韋弦zhy", age: 18), res: nil)
}
func sendData<T: Codable>(_ model: T?, res: ((_ error: Error?) -> Void)?) {
guard let json = model.json() else {
print("json error ")
return
}
print("encoded json: \(json)")
// begin send data
// res?(error)
}
}
extension Encodable {
/// 將model轉換爲json
/// - Returns: json?
func json() -> String? {
var modelJson: String? = nil
do {
let data = try JSONEncoder().encode(self)
modelJson = String(data: data, encoding: .utf8)
} catch {
print(error)
}
return modelJson
}
}
最初開發的時候一切都很正常,不管我傳遞的 model
是 1
還是 "1"
或者是 一個 User
, 代碼跑起來打印如下:
encoded json: 1
encoded json: {"name":"韋弦zhy","age":18}
問題開始
當開始兼容性測試時,iOS 13 系統以下,業務突然完全無法實現,查看 log:
invalidValue(Optional(1), Swift.EncodingError.Context(codingPath: [], debugDescription: "Top-level Optional<Int> encoded as number JSON fragment.", underlyingError: nil))
json error
encoded json: {"name":"韋弦zhy","age":18}
後續測試發現:只有類似 User
這樣的結構體或類才能正常編碼,而基礎類型 Int
, Double
, String
等,均無法編碼成功,可是查看encode
接口並沒有相關描述:
open class JSONEncoder {
...
/// Encodes the given top-level value and returns its JSON representation.
///
/// - parameter value: The value to encode.
/// - returns: A new `Data` value containing the encoded JSON data.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
open func encode<T>(_ value: T) throws -> Data where T : Encodable
}
在 Swift JSONEncoder 的源碼中也翻了翻,也是沒找到關於iOS 版本相關描述,方法實現如下:
open class JSONEncoder {
...
/// Encodes the given top-level value and returns its JSON representation.
///
/// - parameter value: The value to encode.
/// - returns: A new `Data` value containing the encoded JSON data.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
open func encode<T : Encodable>(_ value: T) throws -> Data {
let encoder = _JSONEncoder(options: self.options)
guard let topLevel = try encoder.box_(value) else {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values."))
}
if topLevel is NSNull {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment."))
} else if topLevel is NSNumber {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment."))
} else if topLevel is NSString {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment."))
}
let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue)
do {
return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions)
} catch {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value to JSON.", underlyingError: error))
}
}
}
內部實現會先調用 box_
方法封裝,得到topLevel
, 實際上 box_
內部主要又是調用 box
方法將基礎類型轉換爲NSString
和 NSNumber
(這裏只關注基礎類型,其他的可以自行查看源碼) 所以纔有了encode
中的判斷 NSNumber
和 NSString
然後拋出異常。。。
問題來了。。。iOS 13 之後怎麼就可以了,沒找到代碼。。。有人找到望同步一下
最終,爲了代碼能夠正常運行,改了一下擴展方法, 經過測試,已經可以表現正常,因爲不知道具體生效的版本(萬一是12.x呢),所以判斷寫在了拋出異常的地方,否則可以寫在encode
之前:
extension Encodable {
/// 將model轉換爲json
/// - Returns: json?
func json() -> String? {
var modelJson: String? = nil
do {
let data = try JSONEncoder().encode(self)
modelJson = String(data: data, encoding: .utf8)
} catch {
/// see: https://github.com/apple/swift/blob/56a1663c9859f1283904cb0be4774a4e79d60a22/stdlib/public/SDK/Foundation/JSONEncoder.swift
/// 從源碼也找不到具體是從哪個版本才支持對 Int Double String 等基本類型的的支持
if (self is NSNumber) || (self is NSString) {
return "\(self)"
}
print(error)
}
return modelJson
}
}
問題是解決了,可是,原因還是沒找到。。。。