JSONEncoder 在 Swift 中還是非常常用的,最近項(xiàng)目中有需要將APP數(shù)據(jù)轉(zhuǎn)換為JSON格式之后,再發(fā)送給服務(wù)器的需求,測(cè)試過程中,然后報(bào)了如下錯(cuò)誤:
invalidValue(Optional(1),
Swift.EncodingError.Context(codingPath: [], debugDescription: "Top-level Optional<Int> encoded as number JSON fragment.", underlyingError: nil))
移除業(yè)務(wù)邏輯的話,代碼大概長(zhǎng)這樣:
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轉(zhuǎn)換為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
}
}
最初開發(fā)的時(shí)候一切都很正常,不管我傳遞的 model 是 1 還是 "1" 或者是 一個(gè) User, 代碼跑起來打印如下:
encoded json: 1
encoded json: {"name":"韋弦zhy","age":18}
問題開始
當(dāng)開始兼容性測(cè)試時(shí),iOS 13 系統(tǒng)以下,業(yè)務(wù)突然完全無法實(shí)現(xiàn),查看 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}
后續(xù)測(cè)試發(fā)現(xiàn):只有類似 User 這樣的結(jié)構(gòu)體或類才能正常編碼,而基礎(chǔ)類型 Int , Double, String 等,均無法編碼成功,可是查看encode 接口并沒有相關(guān)描述:
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 的源碼中也翻了翻,也是沒找到關(guān)于iOS 版本相關(guān)描述,方法實(shí)現(xiàn)如下:
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))
}
}
}
內(nèi)部實(shí)現(xiàn)會(huì)先調(diào)用 box_方法封裝,得到topLevel, 實(shí)際上 box_ 內(nèi)部主要又是調(diào)用 box 方法將基礎(chǔ)類型轉(zhuǎn)換為NSString 和 NSNumber(這里只關(guān)注基礎(chǔ)類型,其他的可以自行查看源碼) 所以才有了encode 中的判斷 NSNumber 和 NSString 然后拋出異常。。。
問題來了。。。iOS 13 之后怎么就可以了,沒找到代碼。。。有人找到望同步一下
最終,為了代碼能夠正常運(yùn)行,改了一下擴(kuò)展方法, 經(jīng)過測(cè)試,已經(jīng)可以表現(xiàn)正常,因?yàn)椴恢谰唧w生效的版本(萬一是12.x呢),所以判斷寫在了拋出異常的地方,否則可以寫在encode之前:
extension Encodable {
/// 將model轉(zhuǎn)換為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
/// 從源碼也找不到具體是從哪個(gè)版本才支持對(duì) Int Double String 等基本類型的的支持
if (self is NSNumber) || (self is NSString) {
return "\(self)"
}
print(error)
}
return modelJson
}
}
問題是解決了,可是,原因還是沒找到。。。。