ios - 在 Swift 中创建一个 JSON 对象

标签 ios json swift

我正在尝试从我的 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/

相关文章:

java - Jackson:自定义 JSON 反序列化器

ios - 将转换后的事件从 Observable 直接转发到 BehaviorSubject

android - 如何更改最近应用程序上的磁贴

ios - __IOS_UNAVAIBLE也使其成为__TVOS_UNAVAILABLE吗?

ios - 低功耗蓝牙背景数据 (iBeacons)

java - 通用解析器返回 HashMap 而不是 Pojo

javascript - 在 dojo 中显示 Json 数据

ios - 从 collectionView 显示时获取单元格的 indexPath

ios - 用于存储日期的 CoreData 推荐做法

ios - 获取 LinkedIn 联系人/连接