Правильный json (вы пропускаете запятую между элементами массива ,
)
[{
"_id": "5ccbf88042b2f60ec690a8dd",
"title": "Conference1",
"description": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.",
"cities": [{
"name": "Paris",
"numberOfUsers": "3"
},
{
"name": "Marseille",
"numberOfUsers": "7"
},
{
"name": "Lyon",
"numberOfUsers": "2"
}
]
},
{
"_id": "5ccbf88042b2f60ec690a8dd",
"title": "Conference1",
"description": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.",
"cities": [{
"name": "Paris",
"numberOfUsers": "5"
},
{
"name": "Marseille",
"numberOfUsers": "10"
},
{
"name": "Lyon",
"numberOfUsers": "8"
}
]
}
]
`// MARK: - Element
struct Root: Codable {
let id, title, purpleDescription: String
let cities: [City]
enum CodingKeys: String, CodingKey {
case id = "_id"
case title
case purpleDescription = "description"
case cities
}
}
// MARK: - City
struct City: Codable {
let name, numberOfUsers: String
}
let res = try! JSONDecoder().decode([Root].self,from:data)
print(res)
Редактировать : здесьэто (города это массив)
newEvent.cities = event["cities"] as? [String:String]
должно быть
newEvent.cities = event["cities"] as? [[String:String]]
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options:[])
//Parse JSON Data
if let events = jsonResult as? [[String:Any]] {
for event in events {
let newEvent = Event()
newEvent.title = event["title"] as? String
newEvent.eventDescription = event["description"] as? String
newEvent.cities = event["cities"] as? [[String:String]]
for city in newEvent.cities ?? [["no city found": "number of users : 0"]] {
newEvent.name = city["name"] ?? ""
newEvent.numberOfUsers = city["numberOfUsers"] ?? ""
}
eventsArray.append(newEvent)
}
}
}catch {
print(error)
}