ios - 在 Decodable 解码函数中检索 JSON 字符串

标签 ios swift nsobject codable decodable

在解码符合 Decodable 的 ClassA 时,我想检索其中一个属性的值以进行自定义解码。我该如何实现?

class ClassA: Decodable {

    let title: String?
    let data: MyCustomNotDecodableNSObject?

    private enum CodingKeys: String, CodingKey {
        case title
        case data
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        title = try? container.decode(String.self, forKey: .title)

        let dataRawValue = ? // somehow retrieve the raw value that coresponds to the key "data" (JSON string)
        let theData = MyCustomNotDecodableNSObject(rawData: dataRawValue)
        data = theData
    }
}

解析的 JSON 示例:

{
    "classA" : {
         "title" = "a title"
         "data" : {
             "key1" : "value 1",
             "key2" : "value 2",
             "key3" : "value 3"
          }
} 

我追求的是:

"key1" : "value 1",
"key2" : "value 2",
"key3" : "value 3"

请不要建议让 MyCustomNotDecodableNSObject 符合 Decodable 协议(protocol)。无法修改此类。

最佳答案

做这个有点难。我发现的一种方法是首先使用此 post 中描述的方法将您想要的部分解码为 [String: Any] .然后,使用 JSONSerialization 将该字典转换为 Data,这是一种相当冗长的做事方式,但我找不到更好的方法。

if let dict = try container.decodeIfPresent([String: Any].self, forKey: .data) {
    let dataRawValue = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) // prettyPrinted is optional here
    data = MyCustomNotDecodableNSObject(rawData: dataRawValue)
} else {
    data = nil
}

如果你真的想要一个 String 传递给 MyCustomNotDecodableNSObject.init,只需调用 String.init(data:encoding:)

需要链接帖子的扩展!

关于ios - 在 Decodable 解码函数中检索 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56823706/

相关文章:

iphone - 像google plus一样查看开关

ios - 链接错误 iOS

ios - 如何在 Xamarin.iOS 中使用动画移动 map 注释?

ios - 如何使用 SwiftyJson 在 1 NSObject 中初始化 json 中的多个字典

ios - 带有对象/参数的 NSObject 自定义初始化

ios - 具有 NSObject 继承的通用类, self.setValue(, forKey : ) not work

ios - Amazon S3 阻止从 URL 访问文件

swift - 注册 AWSS3 配置造成 5000 多次内存泄漏

ios - 在 UIView 中移动和缩放 UIImageView

ios - 如何使用photokit获取图片库中存储的所有视频文件的url