我已经创建了下一个字典:

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

得到:

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

那么,如何将其转换为JSON呢?


当前回答

斯威夫特3:

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

其他回答

斯威夫特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。字符串、整型和双精度(以及更多)已经是可编码的。参见编码和解码自定义类型。

还要注意,Any不符合Codable。这可能仍然是一个很好的方法来调整你的数据成为可编码的,这样你就可以使用Swift类型(特别是在你也要解码任何编码的json的情况下),这样你就可以更声明你的编码的结果。

使用lldb

(lldb) p JSONSerialization.data(withJSONObject: notification.request.content.userInfo, options: [])
(Data) $R16 = 375 bytes
(lldb) p String(data: $R16!, encoding: .utf8)!
(String) $R18 = "{\"aps\": \"some_text\"}"

//or
p String(data: JSONSerialization.data(withJSONObject: notification.request.content.userInfo, options: [])!, encoding: .utf8)!
(String) $R4 = "{\"aps\": \"some_text\"}"

斯威夫特3:

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

斯威夫特5:

extension Dictionary {
    
    /// Convert Dictionary to JSON string
    /// - Throws: exception if dictionary cannot be converted to JSON data or when data cannot be converted to UTF8 string
    /// - Returns: JSON string
    func toJson() throws -> String {
        let data = try JSONSerialization.data(withJSONObject: self)
        if let string = String(data: data, encoding: .utf8) {
            return string
        }
        throw NSError(domain: "Dictionary", code: 1, userInfo: ["message": "Data cannot be converted to .utf8 string"])
    }
}
 do{
        let dataDict = [ "level" :
                            [
                                ["column" : 0,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],
                                ["column" : 1,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],
                                ["column" : 2,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],
                                ["column" : 0,"down" : 0,"left" : 0,"right" : 0,"row" : 1,"up" : 0],
                                ["column" : 1,"down" : 0,"left" : 0,"right" : 0,"row" : 1,"up" : 0],
                                ["column" : 2,"down" : 0,"left" : 0,"right" : 0,"row" : 1,"up" : 0]
                            ]
        ]
        var jsonData = try JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)
        let jsonStringData =  NSString(data: jsonData as Data, encoding: NSUTF8StringEncoding)! as String
        print(jsonStringData)
    }catch{
        print(error.localizedDescription)
    }