用动态内容解析JSON对象:以低圈复杂度解析JSON对象的最佳方法是什么?
我有一个服务,它以这种形式返回一个对象数组:用动态内容解析JSON对象:以低圈复杂度解析JSON对象的最佳方法是什么?,json,swift,casting,json-deserialization,Json,Swift,Casting,Json Deserialization,我有一个服务,它以这种形式返回一个对象数组: { result: [ { objectId: "id", type: "objectType", content: { ... } }, ... ] } 内容取决于对象类型。我尝试过用这种方式构建自定义解码器(ContentItem是针对ClassA、B等的协议): 这是可行的,但我得到了
{
result: [
{
objectId: "id",
type: "objectType",
content: { ... }
}, ...
]
}
内容取决于对象类型。我尝试过用这种方式构建自定义解码器(ContentItem是针对ClassA、B等的协议):
这是可行的,但我得到了很高的圈复杂度(我的目标是sub-10,但我有14个不同的内容类)。因此,我尝试改变我的方法,将ContentItem作为超类,并将init更改为如下内容:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
objectId = try container.decode(String.self, forKey: .objectId)
let type = try container.decode(String.self, forKey: .type)
let itemTypes: [String: ContentItem.Type] = [
"typeA": ClassA.self,
"typeB": ClassB.self,
...
]
guard let type = type, let contentItemType = itemTypes[type] else { return }
content = try container.decode(contentItemType, forKey: .content)
}
正如我所希望的那样,这降低了圈复杂度,但它不再起作用,因为decode只返回ContentItem(超类)类型的对象,而不是我想要的特定ClassA、ClassB。有没有办法让这种方法奏效?怎么了
更重要的是,有一种更有效的方法来解析这个对象吗?
你可以考虑使用<代码>枚举>代码>来代替这种类型的解码。你有例子吗?案例类型1(类型1对象)
案例类型2(类型2对象)
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
objectId = try container.decode(String.self, forKey: .objectId)
let type = try container.decode(String.self, forKey: .type)
let itemTypes: [String: ContentItem.Type] = [
"typeA": ClassA.self,
"typeB": ClassB.self,
...
]
guard let type = type, let contentItemType = itemTypes[type] else { return }
content = try container.decode(contentItemType, forKey: .content)
}