There is an easy way to do this and a hard way.
The easy way is to just decode the JSON to a dictionary:
import Foundation
struct Response: Codable {
var posts: [String: Post]
}
struct Post: Codable, Identifiable {
var postID : String
var caption: String
var date : String
var imageDownloadURL : String
var id: String { postID }
}
let jsonData = """
{
"posts": {
"-MTal_snEEAdx7wTcqpL": {
"NumberOfLikes": 3,
"caption": "Yellow πππππ moon",
"date": "23 Feb 2021 at 5:56:1 AM",
"edited": true,
"id": "2khpsHcxPZdRApZ2eIXbuOrBajA3",
"imageDownloadURL": "https://-------",
"postID": "-MTal_snEEAdx7wTcqpL"
},
"-MTawPLC_lz-0p18x0CZ": {
"NumberOfLikes": 4,
"caption": "Sunset ππππ",
"date": "23 Feb 2021 at 5:57:55 AM",
"edited": true,
"id": "2khpsHcxPZdRApZ2eIXbuOrBajA3",
"imageDownloadURL": "https://-------------",
"postID": "-MTawPLC_lz-0p18x0CZ"
}
}
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
var response: Response? = nil
do {
response = try decoder.decode(Response.self, from: jsonData)
}
catch {
print(error)
}
print(response)
The hard way involves treating the posts
object of the JSON response as having dynamic keys and then doing something like this article discusses: Decode and Flatten JSON with Dynamic Keys Using Decodable