ios - 如何使用可解码协议(protocol)为具有不同键的相同 Json 属性创建通用类

标签 ios json swift swift4 decodable

{
    "actions" : {
        "upvote" : {
            "delete" : true,
            "read" : true,
            "create" : true,
            "update": true
        },
        "read" : {
            "delete" : true,
            "update" : true,
            "read" : true,
            "create" : true
        }
    }
}

我有这个来自服务器的 Json 响应,下面是使用 Decodable 协议(protocol)创建的模型结构

struct Actions: Decodable {
    let upvote: UpvoteStatus
    let read: ReadStatus

    enum CodingKeys: String, CodingKey {
        case upvote
        case read
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.upvote = try container.decode(UpvoteStatus.self, forKey: .upvote) {
        self.read = try container.decode(ReadStatus.self, forKey: .read)
    }
}

struct UpvoteStatus: Decodable {
    let delete: Bool
    let update: Bool
    let read: Bool
    let create: Bool
}

struct ReadStatus: Decodable {
    var delete: Bool
    var update: Bool
    var read: Bool
    var create: Bool
}

这很好用,但会产生大量重复代码,因为 UpvoteStatus 和 ReadStatus 结构具有相似的属性,并且来自服务器的 JSON 除了键不同外也相似。

有什么方法可以创建一个公共(public)状态结构,将状态属性添加到 ReadStatus 和 UpvoteStatus 类

struct Status: Decodable {
    let delete: Bool
    let update: Bool
    let read: Bool
    let create: Bool
} 

现在我想要像下面这样的东西,这样我就可以删除重复的代码。

struct UpvoteStatus: Decodable {
    let status: Status
}

struct ReadStatus: Decodable {
    let status: Status
}

最佳答案

可能这就是你需要的,也许你想得太认真了:

struct Actions: Decodable {
    let upvote: Status
    let read: Status

    enum CodingKeys: String, CodingKey {
        case upvote
        case read
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.upvote = try container.decode(Status.self, forKey: .upvote) {
        self.read = try container.decode(Status.self, forKey: .read)
    }
}

struct Status: Decodable {
    let delete: Bool
    let update: Bool
    let read: Bool
    let create: Bool
} 

关于ios - 如何使用可解码协议(protocol)为具有不同键的相同 Json 属性创建通用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52165486/

相关文章:

ios - 自定义 WKInterfaceTable 行中的 WKInterfaceLabel 展开为 nil

jquery - Django:如何在jquery中访问JsonResponse字典?

java - Android Studio httpURLConnection 应用程序崩溃

Swift:从父类(super class)访问自己的属性(property)

ios - UICollectionView scrollToItem() 滚动到上一个单元格无法正常工作

ios - NSUserDefaults 导致性能问题

iphone - NSArray 中的字符串到注释、mapkit

javascript - 在 JSON 数组中添加新对象

swift - 使用具有未设置或设置为 NSKeyedUnarchiveFromDataTransformerName 的转换器名称的可转换属性

ios - iPhone 加速度计值