Ich habe das nächste Wörterbuch erstellt:
var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary
und ich erhalte:
[2: B, 1: A, 3: C]
Wie kann ich es also in JSON konvertieren?
Swift 3.0
Mit Swift 3 haben sich der Name von NSJSONSerialization
und seine Methoden geändert, entsprechend den [Swift API Design Guidelines] (https://swift.org/documentation/api-design-guidelines/).
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Schnell 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
Sie gehen von einer falschen Annahme aus. Nur weil der Debugger/Playground Ihr Wörterbuch in eckigen Klammern anzeigt (so zeigt Cocoa Wörterbücher an), bedeutet das nicht, dass die JSON-Ausgabe so formatiert ist.
Hier ist ein Beispielcode, der ein Wörterbuch mit Zeichenketten in JSON konvertiert:
Swift 3 Version:
import Foundation
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .ascii)
print("JSON string = \(theJSONText!)")
}
Um die obigen Angaben im "hübsch gedruckten" Format anzuzeigen, würden Sie die Optionszeile in 'ändern:
options: [.prettyPrinted]
Oder in der Syntax von Swift 2:
import Foundation
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
dictionary ,
options: NSJSONWritingOptions(0),
error: nil)
let theJSONText = NSString(data: theJSONData!,
encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")
Die Ausgabe davon ist
"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"
Oder im hübschen Format:
{
"anotherKey" : "anotherValue",
"aKey" : "aValue"
}
Das Wörterbuch ist in der JSON-Ausgabe in geschweifte Klammern eingeschlossen, so wie Sie es erwarten würden.
In der Syntax von Swift 3/4 sieht der obige Code wie folgt aus:
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: .prettyPrinted
),
let theJSONText = String(data: theJSONData,
encoding: String.Encoding.ascii) {
print("JSON string = \n\(theJSONText)")
}
}
Meine Antwort auf Ihre Frage lautet wie folgt
let dict = ["0": "ArrayObjectOne", "1": "ArrayObjecttwo", "2": "ArrayObjectThree"]
var error : NSError?
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
print(jsonString)
Die Antwort lautet
{
"0" : "ArrayObjectOne",
"1" : "ArrayObjecttwo",
"2" : "ArrayObjectThree"
}