Swift Codable with dynamic keys

前端 未结 3 545
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 13:12

I have JSON structure as:

\"periods\": {
    \"2018-06-07\": [
      {
        \"firstName\": \"Test1\",
        \"lastName\": \"Test1\"
      }
            


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 14:06

    I think the JSON shall be appended with { at the beginning and } at the end in order to be valid JSON, then you can easily extract periods with code like that:

    struct Period: Decodable {
        let firstName: String, lastName: String
    }
    
    let schedule = try? JSONDecoder().decode([String:[String:[Period]]].self, from: jsonData!)
    let periods = schedule?.values.first?.values
    

提交回复
热议问题