在Swift中,如何将具有任何类型值的字典转换为JSON字符串

时间:2016-01-20 02:58:05

标签: json swift

如果字典是[String:String],我知道如何将它转换为JSON字符串。

但是,我想知道我是否可以将以下类型的字典转换为JSON字符串?怎么样?

let parameters: [String:Any] = [
    "Key" : "somekey",
    "cid" : 23,
    "timestamp" : 1732998762,
    "number": 1124,
]

1 个答案:

答案 0 :(得分:1)

试试这段代码:

let parameters: [String:AnyObject] = [
    "Key" : "somekey",
    "cid" : 23,
    "timestamp" : 1732998762,
    "number": 1124,
]

do {

    let theJSONData = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions(rawValue: 0))

    let theJSONText = NSString(data: theJSONData,
        encoding: NSASCIIStringEncoding)

    print(theJSONText)

} catch {

}