Mutaeb Alqahtani
Mutaeb Alqahtani

Reputation: 354

How to write a model struct if the keys of the object are different

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"
  }
}

Upvotes: 0

Views: 61

Answers (1)

Rob
Rob

Reputation: 437552

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)
}

Upvotes: 2

Related Questions