解析具有动态内容的 JSON 对象:以低圈复杂度进行解析的最佳方法是什么?

问题描述

我有一个以这种形式返回对象数组的服务:

{
    result: [
        {
            objectId: "id",type: "objectType",content: { ... }
        },...
    ]
}

内容取决于对象类型。我尝试以这种方式构建自定义解码器(ContentItem 是 ClassA、B 等的协议):

struct ContentDataItem: Decodable {
    var objectId: String?
    var type: String?
    var content: ContentItem?
    private enum CodingKeys: String,CodingKey {
        case objectId
        case type
        case content
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        objectId = try container.decode(String.self,forKey: .objectId)
        type = try container.decode(String.self,forKey: .type)
        if let type = type {
            switch type {
            case "typeA":
                content = try container.decode(ClassA.self,forKey: .content)
            case "typeB":
                content = try container.decode(ClassB.self,forKey: .content)
                ...
            }
        }
    }
}

这行得通,但我的圈复杂度很高(我的目标是低于 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。有没有办法使这种方法起作用?有什么问题吗?

更重要的是,有没有更有效的方法来解析这个对象?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)