Swift 4解码简单的根级别JSON值 [英] Swift 4 decode simple root level json value
问题描述
根据JSON标准 RFC 7159 ,这是有效的json:
According to the JSON standard RFC 7159, this is valid json:
22
如何使用swift4的可解码功能将其解码为Int?这不起作用
How do I decode this into an Int using swift4's decodable? This does not work
let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
推荐答案
它可以很好地与 JSONSerialization
和 .allowFragments
阅读选项。从文档:
allowFragments
指定解析器应允许不是其实例的顶级对象NSArray或NSDictionary。
Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
示例:
let json = "22".data(using: .utf8)!
if let value = (try? JSONSerialization.jsonObject(with: json, options: .allowFragments)) as? Int {
print(value) // 22
}
但是, JSONDecoder
没有此类选项,并且不接受不是数组或字典的顶级
对象。可以在
源代码中看到 decode()
方法调用
JSONSerialization.jsonObject()
时,没有任何选择:
However, JSONDecoder
has no such option and does not accept top-level
objects which are not arrays or dictionaries. One can see in the
source code that the decode()
method calls
JSONSerialization.jsonObject()
without any option:
open func decode<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
}
这篇关于Swift 4解码简单的根级别JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!