iOS 错误“JSON 写入中的类型无效 (FIRTimestamp)”

问题描述 投票:0回答:4

我正在尝试将我的数据映射到模型。 我在其中使用 Firestore 快照侦听器来获取数据。 在这里,我正在获取数据并映射到“用户”模型

            do{
                let user = try User(dictionary: tempUserDic)
                print("\(user.firstName)")
            }
            catch{
                print("error occurred")
            }

这是我的型号:

struct User {
    let firstName: String
//    var lon: Double = 0.0
//    var refresh:Int = 0
//    var createdOn: Timestamp = Timestamp()
}

//Testing Codable
extension User: Codable {
    init(dictionary: [String: Any]) throws {
        self = try JSONDecoder().decode(User.self, from: JSONSerialization.data(withJSONObject: dictionary))
    }
    private enum CodingKeys: String, CodingKey {
        case firstName = "firstName"
    }
}

如果我错了请纠正我。

崩溃,因为我在数据中获取“时间戳”。

从监听器获取数据:

用户词典

[\"firstName\": Ruchira,
 \"lastInteraction\": FIRTimestamp: seconds=1576566738 nanoseconds=846000000>]"

如何将“时间戳”映射到模型?

尝试过“CodableFirstore”https://github.com/alickbass/CodableFirebase

ios firebase swift4 codable
4个回答
2
投票

一种方法是创建类型

Dictionary
的扩展,将字典转换为任何其他类型,但自动将
Date
Timestamp
类型修改为可写 JSON 字符串。

这是代码:

extension Dictionary {

    func decodeTo<T>(_ type: T.Type) -> T? where T: Decodable {
        
        var dict = self

        // This block will change any Date and Timestamp type to Strings
        dict.filter {
            $0.value is Date || $0.value is Timestamp
        }.forEach {
            if $0.value is Date {
                let date = $0.value as? Date ?? Date()
                dict[$0.key] = date.timestampString as? Value
            } else if $0.value is Timestamp {
                let date = $0.value as? Timestamp ?? Timestamp()
                dict[$0.key] = date.dateValue().timestampString as? Value
            }
        }

        let jsonData = (try? JSONSerialization.data(withJSONObject: dict, options: [])) ?? nil
        if let jsonData {
            return (try? JSONDecoder().decode(type, from: jsonData)) ?? nil
        } else {
            return nil
        }
    }
}

.timestampString
方法也在类型
Date
的扩展中声明:

extension Date {
    
    var timestampString: String {
        Date.timestampFormatter.string(from: self)
    }
    
    static private var timestampFormatter: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.timeZone = TimeZone(identifier: "UTC")
        return dateFormatter
    }
}

用法,就像问题中的情况一样:

let user = tempUserDict.decodeTo(User.self)

0
投票

我通过将

FIRTimestamp
字段转换为
Double
(秒)解决了这个问题,这样
JSONSerialization
就可以相应地解析它。

 let items: [T] = documents.compactMap { query in
   var data = query.data() // get a copy of the data to be modified.

   // If any of the fields value is a `FIRTimestamp` we replace it for a `Double`.
   if let index = (data.keys.firstIndex{ data[$0] is FIRTimestamp }) {

     // Convert the field to `Timestamp`
     let timestamp: Timestamp = data[data.keys[index]] as! Timestamp

     // Get the seconds of it and replace it on the `copy` of `data`.
     data[data.keys[index]] = timestamp.seconds

    }

    // This should not complain anymore.
    guard let data = try? JSONSerialization.data(
       withJSONObject: data, 
       options: .prettyPrinted
    ) else { return nil }

    // Make sure your decoder setups the decoding strategy to `. secondsSince1970` (see timestamp.seconds documentation).
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .secondsSince1970
    return try? decoder.decode(T.self, from: data)
 }

// Use now your beautiful `items`
return .success(items)


0
投票

我发现 Firestore 本身通过

documentReference.data(as: )
处理时间戳转换;因此,您不必自己访问数据字典,而是可以将其传入,例如:
documentReference.data(as: User.self)

现有的解决方案实现了额外的解码逻辑,我相信这些逻辑应该已经通过

Timestamp
与 Codable 的一致性来处理。他们会遇到嵌套时间戳的问题。

  • 通过firebase文档
    Use documentReference.data(as: ) to map a document reference to a Swift type.

0
投票

虽然使用 Firebase 解码器中的构建是理想的,但模型类结构的更改将使其损坏。就我而言,我捕获错误,然后更正传入的记录数据,以便可以对其进行解码。 这是一种扩展 @mig_loren 答案的方法,但修复了所有属性,包括通过数组和子字典进行递归。

private func fixFirTimestamps(_ jsonDict: [String: Any]) -> [String: Any] {
    var fixedDict = jsonDict
    
    // Find all fields where value is a `FIRTimestamp` and replace it with `Double`.
    let indices = fixedDict.keys.indices.filter { index in
        let key = fixedDict.keys[index]
        return jsonDict[key] is Timestamp
    }
    
    // replace `Timestamp` with `Double`
    for index in indices {
        let key = fixedDict.keys[index]
        guard let timestamp = fixedDict[key] as? Timestamp else { continue }
        fixedDict[key] = timestamp.seconds
    }

    // find child json and recurse
    let childJsonIndices = fixedDict.keys.indices.filter { index in
        let key = fixedDict.keys[index]
        return jsonDict[key] is [String: Any]
    }
    
    // recurse child json
    for index in childJsonIndices {
        let key = fixedDict.keys[index]
        guard let childJson = fixedDict[key] as? [String: Any] else { continue }
        fixedDict[key] = fixFirTimestamps(childJson)
    }
    
    // find arrays of child json and recurse
    let childJsonArrayIndices = fixedDict.keys.indices.filter { index in
        let key = fixedDict.keys[index]
        return jsonDict[key] is [[String: Any]]
    }
    
    // recurse child json
    for index in childJsonArrayIndices {
        let key = fixedDict.keys[index]
        guard let childJsonArray = fixedDict[key] as? [[String: Any]] else { continue }
        let updatedArray = childJsonArray.map { childJson in
            return fixFirTimestamps(childJson)
        }
        fixedDict[key] = updatedArray
    }
    
    return fixedDict
}

// call with 
let fixedDict = fixFirTimestamps(query.data())
© www.soinside.com 2019 - 2024. All rights reserved.