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

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

得到:

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

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


当前回答

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

其他回答

这对我来说很管用:

import SwiftyJSON

extension JSON {
    
    mutating func appendIfKeyValuePair(key: String, value: Any){
        if var dict = self.dictionaryObject {
            dict[key] = value
            self = JSON(dict)
        }
    }
}

用法:

var data: JSON = []

data.appendIfKeyValuePair(key: "myKey", value: "myValue")
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
}

斯威夫特3:

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

这是一个简单的扩展来做到这一点:

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
    }

}

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