Ios 在可解码解码函数中检索JSON字符串
在对符合Decodable的ClassA进行解码的过程中,我想检索自定义解码的一个属性的值。我如何做到这一点Ios 在可解码解码函数中检索JSON字符串,ios,swift,nsobject,codable,decodable,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 } req
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符合可解码协议。这个类不能修改。这样做有些困难。我发现的一种方法是,首先使用本文中描述的方法将您想要的部分解码为
[String:Any]
。然后,使用JSONSerialization
将字典转换为数据,这是一种相当冗长的方法,但我找不到更好的方法
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
}
如果您确实想将字符串
传递到MyCustomNotDecodableNSObject.init
,只需调用String.init(数据:编码:)
需要链接帖子的扩展请添加输入和输出示例您是否希望dataRawValue
类型为Data
?您好,但为什么MyCustomNotDecodablesObject不应是可解码的?如果您的类型符合decodable,那么您可以轻松解码这样的值,let dataRawValue=try?container.decode(MyCustomNotDecodableNSObject.self,forKey:.data)
@Andrew请不要建议使MyCustomNotDecodableNSObject符合可解码协议。无法修改此类。您的更新没有回答我的问题“您希望获取<代码>数据代码>?还是希望将其作为字符串获取?”。需要链接文章的扩展名!