【问题标题】:Decode Arbitrary JSON in Swift在 Swift 中解码任意 JSON
【发布时间】:2021-07-20 07:18:35
【问题描述】:

我正在尝试解码具有以下结构的 JSON 并转换为 Swift 结构对象。

"{\"createdAt\":\"2021-07-20T06:53:05.755Z\",\"extraPayload\":\"32bd7d6691964519\",\"messageID\":\"a5f77d0a27da2e14a78ce4d736590bb3c369d5e5bebd36339553e3b699b82d13\",\"publishedAt\":\"2021-07-20T06:53:05.836655Z\"}"

publishedAtmessageID 字段都是固定的,JSON 中的任何其他字段都可以根据特定用例任意设置。 在这种情况下,createdAtextraPayload 两个字段都是完全可选的,而另一种情况可能是 appConfig:true 等,除了 2 个固定字段。

如何映射到具有以下格式的结构,该结构具有 2 个强制固定字段和使用 [String:Any] 类型的字典捕获的任意部分?

public struct MessagePayload {
    /**
     * Message identifier — opaque non-empty string.
     */
    let messageID: String
    
    /**
     * ISO 8601 date indicating a moment when the message was published to the ACN back-end service.
     */
    let publishedAt: String
    
    /**
     * Application-specific fields.
     */
    let messageObject: [String:Any]?
}

我尝试过使用 Swift Codable,但它不支持 [String:Any]。

【问题讨论】:

  • 将它们设为可选。 “下面”这个词不是形容词。
  • 我试过可选的。字典未映射。
  • @HariJustForFun 您需要更加明确。 messageObject 有哪些不同的可能性?如果您可以分享至少 2 种样式(在 json 示例中),那么我们可以帮助您探索 Custom Decoders 的世界。
  • 感谢 staticVoidMan。更新了问题。如果更清楚,请告诉我。

标签: swift


【解决方案1】:

看来Foundation 中的JSONSerialization 可能更适合您的用例。这会将 JSON 数据直接解码为 Any 类型,然后您可以将其转换为 [String: Any] 以访问底层属性。

let decoded = try? JSONSerialization.jsonObject(with: myJsonData, options: []) as? [String: Any]
decoded?["messageID"]
decoded?["publishedAt"]
// ...access other properties as needed

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    相关资源
    最近更新 更多