Swift's JSONDecoder with multiple date formats in a JSON string?

前端 未结 8 1569
既然无缘
既然无缘 2020-12-14 06:48

Swift\'s JSONDecoder offers a dateDecodingStrategy property, which allows us to define how to interpret incoming date strings in accordance with a

8条回答
  •  青春惊慌失措
    2020-12-14 07:21

    There are a few ways to deal with this:

    • You can create a DateFormatter subclass which first attempts the date-time string format, then if it fails, attempts the plain date format
    • You can give a .custom Date decoding strategy wherein you ask the Decoder for a singleValueContainer(), decode a string, and pass it through whatever formatters you want before passing the parsed date out
    • You can create a wrapper around the Date type which provides a custom init(from:) and encode(to:) which does this (but this isn't really any better than a .custom strategy)
    • You can use plain strings, as you suggest
    • You can provide a custom init(from:) on all types which use these dates and attempt different things in there

    All in all, the first two methods are likely going to be the easiest and cleanest — you'll keep the default synthesized implementation of Codable everywhere without sacrificing type safety.

提交回复
热议问题