0

I am trying to decode this data, but the keys are different, so I am not sure how to set a variable that can capture the unknown key

This is what I am trying to achieve

struct Offer: Decodable {
    let creationDate: Double
    let description: String
    let imageUrl: String
    let phoneNumber: String
}

This the JSON

{
  "-Ll3YgwlwuV0AbZSwhAK": {
    "creationDate": 1564518305.580168,
    "description": "Hehbs",
    "imageUrl": "https://firebasestorage.googleapis.com/",
    "phoneNumber": "458194954"
  },
  "-Ll3ZWpOxPvep66qzEK6": {
    "creationDate": 1564518522.191582,
    "description": "Jenner",
    "imageUrl": "https://firebasestorage.googleapis.com/",
    "phoneNumber": "51554"
  },
  "-Ll3jq39mEjHS0AsycEz": {
    "creationDate": 1564521488.6788402,
    "description": "Jwd\t\t",
    "imageUrl": "https://firebasestorage.googleapis.com/",
    "phoneNumber": "dwjd"
  },
  "-Ll3l2u_zqi1JLrJ_049": {
    "creationDate": 1564521807.552466,
    "description": "like",
    "imageUrl": "https://firebasestorage.googleapis.com/",
    "phoneNumber": "kkef"
  },
  "-Ll3lSVfdKGGtMMuTcDg": {
    "creationDate": 1564521912.391248,
    "description": "Mmm",
    "imageUrl": "https://firebasestorage.googleapis.com/",
    "phoneNumber": "mm"
  }
}
Mutaeb Alqahtani
  • 354
  • 4
  • 13
  • The keys of the JSON dictionary becomes keys of a Swift `[OfferID: Offer]` dictionary – Alexander Jul 30 '19 at 22:23
  • Likely duplicate of https://stackoverflow.com/questions/45598461/swift-4-decodable-with-keys-not-known-until-decoding-time – matt Jul 30 '19 at 22:24
  • Or possibly https://stackoverflow.com/questions/57262426/swift-codable-decode-dictionary-with-unknown-keys – matt Jul 30 '19 at 22:26

1 Answers1

2

You can also decode it with:

let dictionary = try JSONDecoder().decode([String: Offer].self, from: data)

For what it’s worth, I’d be inclined to make the creationDate a Date and the imageUrl a URL:

struct Offer: Decodable {
    let creationDate: Date
    let description: String
    let imageUrl: URL
    let phoneNumber: String
}

And then you can decode it with:

do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .secondsSince1970
    let dictionary = try decoder.decode([String: Offer].self, from: data)
    print(dictionary)
} catch {
    print(error)
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044