它可以很好地
JSONSerialization与
.allowFragments
阅读选项配合使用。从文档中:
allowFragments指定解析器应允许不是NSArray或NSDictionary实例的顶级对象。
例:
let json = "22".data(using: .utf8)!if let value = (try? JSONSerialization.jsonObject(with: json, options: .allowFragments)) as? Int { print(value) // 22}但是,
JSONDeprer没有这样的选项,并且不接受不是数组或字典的顶级对象。可以在
源代码中看到该
depre()方法调用
JSONSerialization.jsonObject()而没有任何选择:
open func depre<T : Decodable>(_ type: T.Type, from data: Data) throws -> T { let topLevel: Any do { topLevel = try JSONSerialization.jsonObject(with: data) } catch { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error)) } // ... return value}


