Search code examples
swiftcodabledecodable

Facing difficulties to define a type for a specific key while decoding JSON


I have come across a key type in the JSON added bellow,

{
   "id": "B2CAA3C8-077B-4A49-B5BA-206709630138",
   "markAsDoneDate": null,
   "endDate": 735025126.41189,
   "type": {
       "ascendingSort": {}
   },
   "createdAt": 726385126.411889
}

Kind of struggling to define any type for the key. Anything I specify it gives me a typeMismatch error. Is there anyway to decode this kind of key?


Solution

  • The solution depends on your needs. Let's say you have BarBasedHabit struct. You can either create "wrapper" struct, HabitType for example.

    struct HabitType: Decodable {
        let barBasedHabit: BarBasedHabit
    }
    

    and then define it in the parent decodable struct.

    struct JsonResponse: Decodable {
         let id: String
         let markAsDoneDate: TimeInterval?
         let endDate: TimeInterval
         let type: HabitType
         let createdAt: TimeInterval
     }
    

    Or you can define dictionary [String:BarBasedHabit] as type, and then take value for hardcoded String "barBasedHabit".

    struct JsonResponse: Decodable {
         let id: String
         let markAsDoneDate: TimeInterval?
         let endDate: TimeInterval
         let type: [String : BarBasedHabit]
         let createdAt: TimeInterval
    }