Andrei F
Andrei F

Reputation: 4394

Swift - JSONEncoder - encode date fields separately in a super class

I am very new to swift and I am trying to find a way to use the default encoding for a class that extends Codable and add separate data for certain fields.

For example, I have a class Contact which extends Codable, with a lot of fields and I want to encode dates differently from default (By default JSONEcoder puts dates as timestamps, but I want to use a different format) For simplicity, let's say my class is:

class Contact:Codable {
    var name: String?
    var id: String?
    var birthdate: Date?
} 

For custom encoding I used this link: Using Decodable in Swift 4 with Inheritance

The issue is that I do not want to encode each field separately because the default encode does this. I just want to add only certain values to the encoded json.

I also found this link about dynamic keys but I don't know how to use it exactly: https://gist.github.com/samwize/a82f29a1fb34091cd61fc06934568f82

Can this be done?

Upvotes: 1

Views: 1301

Answers (1)

Sweeper
Sweeper

Reputation: 271820

If you just want to encode dates differently, you can set the dateEncodingStrategy of the JSONEncoder to one of the preset values.

You might want to set it to .custom or formatted if your way of encoding is very special.

encoder.dateEncodingStrategy = .custom({
    date, encoder in
    ...
})
// or
let formatter = DateFormatter()
formatter.dateFormat = "some format"
encoder.dateEncodingStrategy = .formatted(formatter)

Upvotes: 2

Related Questions