我正在尝试从我的 iOS 应用程序向服务器发送 JSON 数据。我在 this link. 上找到了教程
“obj: AnyObject”应该是什么样子才能调用这个方法:
NSJSONSerialization.dataWithJSONObject(obj: AnyObject, options: NSJSONWritingOptions, error: NSErrorPointer)
它不接受字典(即使它以某种方式在上面链接的示例中使用)或数组。
最佳答案
假设你有一本像
这样的字典let dictionary = ["key1": "value1", "key2": "value2"]
要使用您提供的方法生成您的 JSON 数据,您只需调用它:
var jsonGenerationError: NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted, error: &jsonGenerationError)
您可以通过解析生成的数据来验证它是否有效:
var jsonParsingError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments, error:&jsonParsingError)
swift 4
let dictionary = ["key1": "value1", "key2": "value2"]
let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
// Verifying it worked:
let parsedObject = try! JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)
关于ios - 在 Swift 中创建一个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263679/