alickbass / CodableFirebase

Use Codable with Firebase
MIT License
692 stars 91 forks source link

How to parse the JSON with multiple structs? #99

Open breakingbeats opened 4 years ago

breakingbeats commented 4 years ago

How can I parse the following Firebase Realtime Database JSON?

firebase data

let firebaseRef = Database.database().reference() firebaseRef.observe(.value, with: { (snapshot) in

guard let value = snapshot.value as? [String: [String: [String: Any]]] else { return print("type wrong") }
    do {
        let model = try FirebaseDecoder().decode(AllData.self, from: Array(value.values))
        print("model:", model)
    } catch let error {
         print("error", error)
    }

})

...and the following structs...

struct AllData: Codable { let news: News let events: Events let crew: Crew let artists: Artists } /////////////////////////////////// struct News: Codable { let news: NewsDetail }

struct NewsDetail: Codable { let title: String let subtitle: String } //////////////////////////////////// struct Artists: Codable { let artist: NewsDetail }

struct ArtistDetail: Codable { let name: String let image: String } ////////////////////////////////// struct Crew: Codable { let member: Member }

struct Member: Codable { let name: String let image: String } //////////////////////////////////// struct Events: Codable { let event: EventDetail } struct EventDetail: Codable { let title: String let subtitle: String let date: String }

Also with guard let value = snapshot.value as? [String:Any] gives me a typeMismatch(Swift.Dictionary<Swift.String, Any>) error. Can anyone help?