在Swift中将字典转换为JSON

我已经创build了下一个词典:

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

我得到:

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

那么,我怎样才能把它转换成JSON呢?

Swift 3.0

使用Swift 3,根据Swift APIdevise指南 , NSJSONSerialization的名称及其方法已经改变。

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

斯威夫特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 } } 

你正在做一个错误的假设。 仅仅因为debugging器/游乐场在方括号中显示你的字典(这是Cocoa如何显示字典)并不意味着这是JSON输出格式化的方式。

以下是将string字典转换为JSON的示例代码:

Swift 3版本:

 import UIKit import AVFoundation 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!)") } 

要以“漂亮打印”格式显示上述内容,您需要将选项行更改为:

  options: [.prettyPrinted] 

或者在Swift 2语法中:

 import UIKit import AVFoundation 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!)") 

这是输出

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

或者以相当的格式:

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

正如您所期望的那样,字典在JSON输出中用大括号括起来。

编辑:

在Swift 3/4语法中,上面的代码看起来像这样:

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

}

我的答案是你的问题在下面

 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) 

答案是

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

有时需要打印出服务器的响应以进行debugging。 这是我使用的一个函数:

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

使用示例:

 (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 2.1

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

Swift 3

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