2016-04-08 23 views
8

Ich weiß, es gibt eine Frage mit dem gleichen Titel here. Aber in dieser Frage versucht er ein Wörterbuch in JSON zu konvertieren. Aber ich habe einen einfachen Stich wie folgt: "Garten"Konvertieren Sie eine einfache Zeichenfolge in JSON String in Swift

Und ich muss es als JSON senden. Ich habe SwiftyJSON versucht, aber ich kann das nicht in JSON konvertieren.

Hier ist mein Code:

Mein Code stürzt in der letzten Zeile:

fatal error: unexpectedly found nil while unwrapping an Optional value 

Mache ich etwas falsch?

Antwort

18

JSON has to be an array or a dictionary kann es nicht nur ein String sein.

Ich schlage vor, Sie einen Array mit String in ihm erstellen:

let array = ["garden"] 

Sie dann ein JSON-Objekt aus diesem Array erstellen:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
    // here `json` is your JSON data 
} 

Wenn Sie das JSON als String benötigen statt Daten können Sie verwenden:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
    // here `json` is your JSON data, an array containing the String 
    // if you need a JSON string instead of data, then do this: 
    if let content = String(data: json, encoding: NSUTF8StringEncoding) { 
     // here `content` is the JSON data decoded as a String 
     print(content) 
    } 
} 

Drucke:

[ „Garten“]

Wenn Sie es vorziehen, ein Wörterbuch, anstatt ein Array ist, folgen die gleiche Idee: schaffen Sie das Wörterbuch dann konvertieren.

let dict = ["location": "garden"] 

if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) { 
    if let content = String(data: json, encoding: NSUTF8StringEncoding) { 
     // here `content` is the JSON dictionary containing the String 
     print(content) 
    } 
} 

Drucke:

{ "Lage": "Garten"}

1

Swift 3 Version:

let location = ["location"] 
    if let json = try? JSONSerialization.data(withJSONObject: location, options: []) { 
     if let content = String(data: json, encoding: .utf8) { 
      print(content) 
     } 
    } 
Verwandte Themen