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"}