Can Swift 4's JSONDecoder be used with Firebase Realtime Database?

后端 未结 7 1764
有刺的猬
有刺的猬 2020-12-28 19:39

I am trying to decode data from a Firebase DataSnapshot so that it can be decoded using JSONDecoder.

I can decode this data fine when I use a URL to access it with a

7条回答
  •  粉色の甜心
    2020-12-28 20:30

    I've converted Firebase Snapshots using JSONDecoder by converting snapshots back to JSON in Data format. Your struct needs to conform to Decodable or Codable. I've done this with SwiftyJSON but this example is using JSONSerialization and it still works.

    JSONSnapshotPotatoes {
        "name": "Potatoes",
        "price": 5,
    }
    JSONSnapshotChicken {
        "name": "Chicken",
        "price": 10,
        "onSale": true
    }
    
    struct GroceryItem: Decodable {
        var name: String
        var price: Double
        var onSale: Bool? //Use optionals for keys that may or may not exist
    }
    
    
    Database.database().reference().child("grocery_item").observeSingleEvent(of: .value, with: { (snapshot) in
            guard let value = snapshot.value as? [String: Any] else { return }
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: value, options: [])
                let groceryItem = try JSONDecoder().decode(GroceryItem.self, from: jsonData)
    
                print(groceryItem)
            } catch let error {
                print(error)
            }
        })
    

    Please note that if your JSON keys are not the same as your Decodable struct. You'll need to use CodingKeys. Example:

    JSONSnapshotSpinach {
        "title": "Spinach",
        "price": 10,
        "onSale": true
    }
    
    struct GroceryItem: Decodable {
        var name: String
        var price: Double
        var onSale: Bool?
    
        enum CodingKeys: String, CodingKey {
            case name = "title"
    
            case price
            case onSale
        }
    }
    

    You can find more information on this using Apple Docs here.

提交回复
热议问题