我创建了下一个字典:
var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary
我得到:
[2: B, 1: A, 3: C]
那么,如何将其转换为JSON?
我创建了下一个字典:
var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary
我得到:
[2: B, 1: A, 3: C]
那么,如何将其转换为JSON?
Answers:
斯威夫特3.0
NSJSONSerialization
根据Swift API设计指南,对于Swift 3,其名称及其方法已更改。
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)
}
斯威夫特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
}
}
[2: A, 1: A, 3: A]
。但是花括号呢?
{"result":[{"body":"Question 3"}] }
dataWithJSONObject
将产生“花括号”(即花括号)作为结果NSData
对象的一部分。
您做出错误的假设。仅仅是因为调试器/游乐场将您的字典显示在方括号中(这就是Cocoa如何显示字典),但这并不意味着这是JSON输出格式化的方式。
这是将字符串字典转换为JSON的示例代码:
Swift 3版本:
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!)")
}
要以“漂亮打印”格式显示以上内容,您可以将选项行更改为:
options: [.prettyPrinted]
或使用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!)")
的输出是
"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)")
}
}
斯威夫特5:
let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
}
请注意,键和值必须实现Codable
。字符串,整数和双打(以及更多)已经存在Codable
。请参见编码和解码自定义类型。
我对你问题的回答如下
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"
}
Swift 4 Dictionary
扩展。
extension Dictionary {
var jsonStringRepresentation: String? {
guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
options: [.prettyPrinted]) else {
return nil
}
return String(data: theJSONData, encoding: .ascii)
}
}
encoding: .ascii
在公共扩展中使用它不是一个好主意。.utf8
会更安全!
有时出于调试目的,有必要打印出服务器的响应。这是我使用的功能:
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"
}
这是执行此操作的简单扩展:
https://gist.github.com/stevenojo/0cb8afcba721838b8dcb115b846727c3
extension Dictionary {
func jsonString() -> NSString? {
let jsonData = try? JSONSerialization.data(withJSONObject: self, options: [])
guard jsonData != nil else {return nil}
let jsonString = String(data: jsonData!, encoding: .utf8)
guard jsonString != nil else {return nil}
return jsonString! as NSString
}
}
private func convertDictToJson(dict : NSDictionary) -> NSDictionary?
{
var jsonDict : NSDictionary!
do {
let jsonData = try JSONSerialization.data(withJSONObject:dict, options:[])
let jsonDataString = String(data: jsonData, encoding: String.Encoding.utf8)!
print("Post Request Params : \(jsonDataString)")
jsonDict = [ParameterKey : jsonDataString]
return jsonDict
} catch {
print("JSON serialization failed: \(error)")
jsonDict = nil
}
return jsonDict
}
NSJSONSerialization