Flattening JSON when keys are known only at runtime

后端 未结 2 1985
予麋鹿
予麋鹿 2020-12-18 17:11

Let\'s say we have a JSON structure like the following (commonly used in Firebase\'s Realtime Database):

{
  \"18348b9b-9a49-4e04-ac35-37e38a8db1e2\": {
             


        
2条回答
  •  醉话见心
    2020-12-18 17:47

    Base entity:

    struct BoringEntity: Decodable {
        let id: String
        let isActive: Bool
        let age: Int
        let company: String
    }
    

    Solution 1: Using an extra struct without the key

    /// Incomplete BoringEntity version to make Decodable conformance possible.
    private struct BoringEntityBare: Decodable {
        let isActive: Bool
        let age: Int
        let company: String
    }
    
    // Decode to aux struct
    private let decoded = try! JSONDecoder().decode([String : BoringEntityBare].self, from: jsonData)
    // Map aux entities to BoringEntity
    let entities = decoded.map { BoringEntity(id: $0.key, isActive: $0.value.isActive, age: $0.value.age, company: $0.value.company) }
    print(entities)
    

    Solution 2: Using a wrapper

    Thanks to Code Different I was able to combine my approach with his PhantomKeys idea, but there's no way around it: an extra entity must always be used.

    struct BoringEntities: Decodable {
        var entities = [BoringEntity]()
    
        // This really is just a stand-in to make the compiler happy.
        // It doesn't actually do anything.
        private struct PhantomKeys: CodingKey {
            var intValue: Int?
            var stringValue: String
            init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
            init?(stringValue: String) { self.stringValue = stringValue }
        }
    
        private enum BareKeys: String, CodingKey {
            case isActive, age, company
        }
    
        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: PhantomKeys.self)
    
            // There's only one key
            for key in container.allKeys {
                let aux = try container.nestedContainer(keyedBy: BareKeys.self, forKey: key)
    
                let age = try aux.decode(Int.self, forKey: .age)
                let company = try aux.decode(String.self, forKey: .company)
                let isActive = try aux.decode(Bool.self, forKey: .isActive)
    
                let entity = BoringEntity(id: key.stringValue, isActive: isActive, age: age, company: company)
                entities.append(entity)
            }
        }
    }
    
    let entities = try JSONDecoder().decode(BoringEntities.self, from: jsonData).entities
    print(entities)
    

提交回复
热议问题