斯威夫特4解码单根水平JSON价值

问题描述:

根据JSON标准RFC 7159,这是有效的JSON:斯威夫特4解码单根水平JSON价值

22 

如何使用swift4的解码解码我到一个诠释呢?这不起作用

let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!) 
+1

这不是一个有效的JSON,一个JSON是键和值对制成,它只是一个值。 –

+2

这是有效的JSON片段,不是有效的JSON。 – Sulthan

+0

我想这取决于使用的标准。在这里查看RFC 7159 https://jsonformatter.curiousconcept.com/。也可以说它是有效的https://tools.ietf.org/html/rfc7159#section-3 – saph

它与良好的醇” JSONSerialization.allowFragments 码扫描选项。从documentation

allowFragments

指定解析器应该允许不NSArray的NSDictionary的或的实例顶层对象。

实施例:

let json = "22".data(using: .utf8)! 

if let value = (try? JSONSerialization.jsonObject(with: json, options: .allowFragments)) as? Int { 
    print(value) // 22 
} 

然而,JSONDecoder没有这样的选项,并且不接受顶层 对象哪些不是阵列或字典。人们可以在 source codedecode()方法调用 JSONSerialization.jsonObject()没有任何选项,请参阅:

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 
} 
+1

您可以尝试在Apple提交错误报告。 –