在Swift中创build一个JSON对象
我试图从我的iOS应用程序发送JSON数据到服务器。 我在这个链接上find了一个教程。
“obj:AnyObject”应该怎么样才能调用这个方法:
NSJSONSerialization.dataWithJSONObject(obj: AnyObject, options: NSJSONWritingOptions, error: NSErrorPointer)
它不接受Dictionary(即使它在上面的链接的例子中以某种方式使用)或数组。
假设你有一本像这样的字典
let dictionary = ["key1": "value1", "key2": "value2"]
要使用您提供的方法生成JSON数据,请将其称为:
var jsonGenerationError: NSError? let jsonData = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted, error: &jsonGenerationError)
您可以通过parsing生成的数据来validation它是否工作:
var jsonParsingError: NSError? let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments, error:&jsonParsingError)