Es arbeitet mit guten alten JSONSerialization
und der .allowFragments
Lesen Option. Von den documentation:
allowFragments
Gibt an, dass der Parser Top-Level-Objekte ermöglichen sollte, keine Instanz von NSArray oder NSDictionary sind.
Beispiel:
let json = "22".data(using: .utf8)!
if let value = (try? JSONSerialization.jsonObject(with: json, options: .allowFragments)) as? Int {
print(value) // 22
}
hat jedoch JSONDecoder
keine solche Option und übernimmt keine Top-Level- Objekte, die keine Arrays oder Wörterbücher sind. Man kann in der source code sehen, dass die decode()
Methode JSONSerialization.jsonObject()
ohne Option ruft:
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
}
dies keine gültige Json ist, ein json von Schlüssel-Wert-Paare hergestellt und es ist nur ein Wert. –
Dies ist ein gültiges JSON-Fragment, kein gültiger JSON. – Sulthan
Ich denke, es hängt vom Standard ab, den man benutzt. Überprüfen Sie RFC 7159 hier https://jsonformatter.curiousconcept.com/. Auch Quelle, dass es gültig ist https://tools.ietf.org/html/rfc7159#section-3 – saph