wift的JSONDecoder在JSON字符串中具有多种日期格

wift的JSONDecoder在JSON字符串中具有多种日期格

本文介绍了Swift的JSONDecoder在JSON字符串中具有多种日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift的 JSONDecoder 提供了一个 dateDecodingStrategy 属性,该属性使我们可以定义如何根据以下内容来解释传入的日期字符串一个 DateFormatter 对象。

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

但是,我目前正在使用一个同时返回两个日期字符串( yyyy-MM-dd )和日期时间字符串( yyyy-MM-dd HH:mm:ss ),具体取决于属性。有没有办法让 JSONDecoder 处理此问题,因为提供的 DateFormatter 对象只能处理单个 dateFormat 一次?

However, I am currently working with an API that returns both date strings (yyyy-MM-dd) and datetime strings (yyyy-MM-dd HH:mm:ss), depending on the property. Is there a way to have the JSONDecoder handle this, since the provided DateFormatter object can only deal with a single dateFormat at a time?

一个不好的解决方案是重写随附的 Decodable 模型只接受字符串作为其属性,并提供公共 Date getter / setter变量,但这对我来说似乎是一个糟糕的解决方案。有什么想法吗?

One ham-handed solution is to rewrite the accompanying Decodable models to just accept strings as their properties and to provide public Date getter/setter variables, but that seems like a poor solution to me. Any thoughts?

推荐答案

有几种方法可以解决此问题:

There are a few ways to deal with this:


  • 您可以创建一个 DateFormatter 子类,该子类首先尝试使用日期时间字符串格式,如果失败,则尝试使用纯日期格式

  • 您可以提供 .custom Date 解码策略,其中您要求 Decoder 以获得 singleValueContainer(),对字符串进行解码,然后将其传递给所需的任何格式化程序,然后再传递解析的日期

  • 您可以围绕 Date 类型创建一个包装,该包装提供自定义的 init(from:) encode(to:)可以做到这一点(但这并不比 .custom 策略)

  • 您可以按照建议使用纯字符串

  • 您可以提供自定义的 init(from :)在所有使用这些日期并尝试在其中进行其他操作的类型上

  • 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

总而言之,前两种方法很可能是最简单,最简洁的-您将保留 Codable 的默认综合实现。到处都不会牺牲类型安全性。

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.

这篇关于Swift的JSONDecoder在JSON字符串中具有多种日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:27