Swift Codable with dynamic keys

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

I have JSON structure as:

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


        
3条回答
  •  旧巷少年郎
    2020-12-01 13:59

    Assuming you left out the { and } that would surround this block and are required for this to be valid JSON, the following is the simplest solution to getting things parsed, you really don't need to deal with CodingKey at all since your names match the keys in the JSON, so the synthesized CodingKey will work just fine:

    public struct Schedule: Codable {
        public let periods : [String:[Inner]]
    }
    
    public struct Inner: Codable {
        public let firstName: String
        public let lastName: String
    }
    
    let schedule = try? JSONDecoder().decode(Schedule.self, from: json)
    
    print(schedule?.periods.keys)
    
    print(schedule?.periods["2018-06-07"]?[0].lastName)
    

    The key is that the outer JSON is a JSON Object (dictionary/map) with a single key periods The value of that key is another map of arrays. Just break it down like that and everything falls out pretty much automatically.

提交回复
热议问题