JSON序列化返回105个字节,但解码返回Nil



大家星期天快乐。我的数据解码有问题。当我将字典字符串序列化到对象中时,似乎无法解码数据。我试图从firebase中获取匹配项,这适用于我获取用户配置文件时,但不适用于获取匹配项。

func fetchMatches(onCompletion: @escaping (Result<[MatchModel], DomainError>) -> ()){
db.collection("matches").whereField("usersMatched", arrayContains: userId!).getDocuments(completion: {doc, err in
guard let documentSnapshot = doc, err == nil else{
onCompletion(.failure(.downloadError))
return
}
var matchList: [MatchModel] = []
var count = 0
let maxCount = documentSnapshot.documents.count
var hasFailed = false
for document in documentSnapshot.documents{
if hasFailed{ break }

let decoder = JSONDecoder()
var dict = document.data()
for (key, value) in dict {

if let value = value as? Timestamp {

let formatter = DateFormatter()
let newValue = value.dateValue()
formatter.dateStyle = .short
formatter.timeStyle = .none
dict[key] = formatter.string(from: newValue)
}
}

到这里为止,我知道一切都很顺利。Dict包含-

Dictionary
["timestamp": "10/22/22", "usersMatched": <__NSArrayM 0x600002c61680>(
6euZHDmI7PMDcCmft5MfxUW27jI3,
tbcB0ay0YEgZcY9UsZ00WjZ9h893
)
]

下面的数据打印出105个字节,所以有了这些信息,我知道它不是空的,JSONSerialization完成了将dict转换为对象的工作。但当我试图将其解码为FirestoreMatch时,self-match返回空

if let data = try? JSONSerialization.data(withJSONObject: dict, options:[]){   
do{       
let match = try? decoder.decode(FirestoreMatch.self, from: data)

let matchId : String = match!.usersMatched.filter{$0 != self.userId!}.first!
... }
catch{ 
print(error)

错误返回:

typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "timestamp", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))

这是我的FirestoreMatch结构

struct FirestoreMatch: Codable{
let usersMatched: [String]
let timestamp: Date
}

我需要结构的更多信息吗?我不确定为什么匹配返回零

感谢@itaiFerber@flanker@loremipsum和@duncanC,我能够利用解决我的问题

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm/dd/yy"
decoder.dateDecodingStrategy = .formatted(dateFormatter)

最新更新