len*_*nny 3 apple-push-notifications swift codable decodable
iOS 从后台通知返回 json 数据,类型为[AnyHashable : Any]. 有什么方法可以将其解析为实现 Codable 协议的结构吗?
例子 :
// Server sends the following data via apn
{"items": [{"id": "192e7926-7891-44eb-8ca7-f795d8552e84", "text": "some text", "num": 0.7}]}
eapp端接收数据时
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
   print(userInfo["items"])
}
print 语句给出以下输出
Optional(<__NSSingleObjectArrayI 0x283fe80b0>(
  {
    id = "192e7926-7891-44eb-8ca7-f795d8552e84";
    num = "0.7";
    text = "Check test";
  }
))
我已经有一个匹配的可编码结构:
struct Item: Codable {
    let id: UUID
    let text: String
    let num: Double
}
我可以以某种方式Item从 a实例化 an 吗userInfo["items"][0]?显然,仅发送编码的 json 字符串就已经解决了这个问题,但我很感兴趣是否有一种方法可以从 [AnyHashable : Any] 解码为结构Decodable。
谢谢!
您可以使用将 dict 转换为 JSON 对象JSONSerialization.data(withJSONObject: 
您可能需要一个容器结构
struct ItemsCollection: Decodable {
    let items: [Item]
}
        let dict: [AnyHashable: Any] = your dict
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dict)
            let itemsCollection = try JSONDecoder().decode(ItemsCollection.self, from: jsonData)
            //now access it as itemsCollection.items[0]
        }
        catch {
            print(error)
        }
编辑1:您始终可以通过避免使用创建新结构来优化解决方案
        let dict: [AnyHashable: Any] = userInfo["items"][0] //not sure if you would need explicit type casting here, cant debug as I dont have actual object
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dict)
            let item = try JSONDecoder().decode(Item.self, from: jsonData)
            //now access item
        }
        catch {
            print(error)
        }
| 归档时间: | 
 | 
| 查看次数: | 2338 次 | 
| 最近记录: |