는 표준 JSON RFC 7159에 따르면,이 유효 JSON입니까? 이 그것은 JSONSerialization
과 .allowFragments
읽기 옵션 '좋은 똑똑한 작동스위프트 4 디코드 간단한 루트 수준 JSON 값
let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
는 표준 JSON RFC 7159에 따르면,이 유효 JSON입니까? 이 그것은 JSONSerialization
과 .allowFragments
읽기 옵션 '좋은 똑똑한 작동스위프트 4 디코드 간단한 루트 수준 JSON 값
let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)
작동하지 않습니다. 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
는 이러한 옵션이없고 최고 레벨 배열이나 사전 아니다 객체를 허용하지 않습니다. JSON이 키와 값 쌍에 의해 이루어집니다,이 유효한 JSON 아닌
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
}
Apple에서 버그 보고서를 보내실 수 있습니다. –
하고 그냥 값이다 : 하나는
decode()
방법은 옵션없이JSONSerialization.jsonObject()
를 호출하는 source code에서 볼 수 있습니다. –이것은 유효한 JSON 조각이 아니며 유효한 JSON 조각입니다. – Sulthan
표준에 따라 달라집니다. RFC 7159는 https://jsonformatter.curiousconcept.com/에서 확인하십시오. https://tools.ietf.org/html/rfc7159#section-3 – saph