2017-10-16 2 views
1

Nach dem JSON Standard RFC 7159, gilt dies json:Swift 4 dekodieren einfache Root-Ebene json Wert

22 

Wie dekodieren ich dies in ein Int mit swift4 dem dekodierbar? Das funktioniert nicht

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

dies keine gültige Json ist, ein json von Schlüssel-Wert-Paare hergestellt und es ist nur ein Wert. –

+2

Dies ist ein gültiges JSON-Fragment, kein gültiger JSON. – Sulthan

+0

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

Antwort

5

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

Sie können versuchen, einen Fehlerbericht bei Apple einzureichen. –