简体   繁体   English

如何使用Codable解析键值json?

[英]How to parse key value json with Codable?

I want to decode this JSON with Codable. 我想用Codable解码此JSON。 Without yellow highlighted, this solution worked but if highlighted section comes from server, codable not working. 如果未突出显示黄色,则该解决方案有效,但如果突出显示的部分来自服务器,则可编码不起作用。 Please help me. 请帮我。

在此处输入图片说明

My solution is: 我的解决方案是:

    let others : [String: OthersType?]?



    enum OthersType: Codable {
    case int(Int)
    case string(String)
    case bool(Bool)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()

        do {
            self = try .int(container.decode(Int.self))
        } catch DecodingError.typeMismatch {
            do {
                self = try .string(container.decode(String.self))
            } catch DecodingError.typeMismatch {
                do {
                    self = try .bool(container.decode(Bool.self))
                } catch DecodingError.typeMismatch {
                    throw DecodingError.typeMismatch(OthersType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload not of an expected type"))
                }
            }
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .int(let int):
            try container.encode(int)
        case .string(let string):
            try container.encode(string)
        case .bool(let bool):
            try container.encode(bool)
        }
    }

    func getValue(_ ofTheWord: OthersType) -> String {
        var result = String(describing: ofTheWord)
        if result.contains("string(") {
            result = result.replacingOccurrences(of: "string(\"", with: "")
            result.removeLast(2)

        } else if result.contains("int(") {
            result = result.replacingOccurrences(of: "int(", with: "")
            result.removeLast(1)

        } else if result.contains("bool(") {
            result = result.replacingOccurrences(of: "bool(", with: "")
            result.removeLast(1)
        }
        return result
    }
}

How to fix this issue with Swift codable? 如何使用Swift codable解决此问题?

Please check out this Gist I have created for parsing dynamic key based JSON via Decodable . 请查看我为通过Decodable解析基于动态密钥的JSON而创建的Decodable https://gist.github.com/aksswami/f30007b71fe78a6d99fff583b38cc480 https://gist.github.com/aksswami/f30007b71fe78a6d99fff583b38cc480

You can also go through this extensive resource for more Codable basics. 您也可以浏览此广泛的资源,以获得更多的Codable基础知识。 https://benscheirman.com/2017/06/swift-json/ https://benscheirman.com/2017/06/swift-json/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM