Convertir le dictionnaire en JSON dans Swift

J’ai créé le dictionnaire suivant:

var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary 

et je reçois:

 [2: B, 1: A, 3: C] 

Alors, comment puis-je le convertir en JSON?

Swift 3.0

Avec Swift 3, le nom de NSJSONSerialization et ses méthodes ont changé, conformément aux directives de conception de l’API Swift .

 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? [Ssortingng:Ssortingng] { // 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? [Ssortingng:Ssortingng] { // use dictFromJSON } } catch let error as NSError { print(error) } 

Rapide 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? [Ssortingng:Ssortingng] { if error != nil { println(error) } else { // here "decoded" is the dictionary decoded from JSON data } } 

Vous faites une hypothèse erronée. Tout simplement parce que le débogueur / Playground montre votre dictionnaire entre crochets (ce qui correspond à la manière dont Cocoa affiche les dictionnaires) ne signifie pas que le format de la sortie JSON est le même.

Voici un exemple de code qui convertira un dictionnaire de chaînes en JSON:

Version Swift 3:

 import Foundation let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"] if let theJSONData = try? JSONSerialization.data( withJSONObject: dictionary, options: []) { let theJSONText = Ssortingng(data: theJSONData, encoding: .ascii) print("JSON ssortingng = \(theJSONText!)") } 

Pour afficher ce qui précède au format “joli imprimé”, vous devez modifier la ligne d’options pour:

  options: [.prettyPrinted] 

Ou dans la syntaxe Swift 2:

 import Foundation let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"] let theJSONData = NSJSONSerialization.dataWithJSONObject( dictionary , options: NSJSONWritingOptions(0), error: nil) let theJSONText = NSSsortingng(data: theJSONData!, encoding: NSASCIISsortingngEncoding) println("JSON ssortingng = \(theJSONText!)") 

La sortie de cela est

 "JSON ssortingng = {"anotherKey":"anotherValue","aKey":"aValue"}" 

Ou dans un joli format:

 { "anotherKey" : "anotherValue", "aKey" : "aValue" } 

Le dictionnaire est entouré d’accolades dans la sortie JSON, comme prévu.

MODIFIER:

Dans la syntaxe Swift 3/4, le code ci-dessus ressemble à ceci:

  let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"] if let theJSONData = try? JSONSerialization.data( withJSONObject: dictionary, options: .prettyPrinted ), let theJSONText = Ssortingng(data: theJSONData, encoding: Ssortingng.Encoding.ascii) { print("JSON ssortingng = \n\(theJSONText)") } } 

Ma réponse à votre question est ci-dessous

 let dict = ["0": "ArrayObjectOne", "1": "ArrayObjecttwo", "2": "ArrayObjectThree"] var error : NSError? let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted) let jsonSsortingng = NSSsortingng(data: jsonData, encoding: NSUTF8SsortingngEncoding)! as Ssortingng print(jsonSsortingng) 

La réponse est

 { "0" : "ArrayObjectOne", "1" : "ArrayObjecttwo", "2" : "ArrayObjectThree" } 

Parfois, il est nécessaire d’imprimer la réponse du serveur à des fins de débogage. Voici une fonction que j’utilise:

 extension Dictionary { var json: Ssortingng { let invalidJson = "Not a valid JSON" do { let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) return Ssortingng(bytes: jsonData, encoding: Ssortingng.Encoding.utf8) ?? invalidJson } catch { return invalidJson } } func printJson() { print(json) } } 

Exemple d’utilisation:

 (lldb) po dictionary.printJson() { "InviteId" : 2, "EventId" : 13591, "Messages" : [ { "SenderUserId" : 9514, "MessageText" : "test", "RecipientUserId" : 9470 }, { "SenderUserId" : 9514, "MessageText" : "test", "RecipientUserId" : 9470 } ], "TargetUserId" : 9470, "InvitedUsers" : [ 9470 ], "InvitingUserId" : 9514, "WillGo" : true, "DateCreated" : "2016-08-24 14:01:08 +00:00" } 

Swift 4:

 let dic = ["2": "B", "1": "A", "3": "C"] let encoder = JSONEncoder() if let jsonData = try? encoder.encode(dic) { if let jsonSsortingng = Ssortingng(data: jsonData, encoding: .utf8) { print(jsonSsortingng) } } 

Notez que les clés et les valeurs doivent implémenter Codable . Les chaînes, les ints et les doubles (et plus) sont déjà Codable . Voir Codage et décodage de types personnalisés .

Swift 3 :

 let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) let jsonSsortingng = Ssortingng(data: jsonData!, encoding: .utf8)! print(jsonSsortingng) 

La réponse à votre question est ci-dessous:

Swift 2.1

  do { if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(dictDataToBeConverted, options: NSJSONWritingOptions.PrettyPrinted){ let json = NSSsortingng(data: postData, encoding: NSUTF8SsortingngEncoding)! as Ssortingng print(json)} } catch { print(error) } 

Voici une extension facile à faire:

https://gist.github.com/stevenojo/0cb8afcba721838b8dcb115b846727c3

 extension Dictionary { func jsonSsortingng() -> NSSsortingng? { let jsonData = try? JSONSerialization.data(withJSONObject: self, options: []) guard jsonData != nil else {return nil} let jsonSsortingng = Ssortingng(data: jsonData!, encoding: .utf8) guard jsonSsortingng != nil else {return nil} return jsonSsortingng! as NSSsortingng } }