将FIRTimestamp转换为JSON

时间:2018-09-04 20:09:15

标签: json swift firebase google-cloud-firestore

将文档转换为Firebase时遇到问题,但是无法转换FIRTimestamp数据。

<tabs  
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/multifield"
    composite="{Boolean}true"
    fieldLabel="Tabs">
    <field
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/coral/foundation/container"
        name="./tabs">
        <items 
            jcr:primaryType="nt:unstructured">
            <title
                jcr:primaryType="nt:unstructured"
                sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
                fieldDescription="Enter the tab title"
                fieldLabel="Title"
                name="./title"
                required="{Boolean}true"/>
        </items>
    </field>
</tabs>

错误

  

***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'JSON写入(FIRTimestamp)中的类型无效'

2 个答案:

答案 0 :(得分:1)

要从JSON中删除FIRTimestamp

 struct leadDocument: Codable {
        let state: String
        let details: String
     }
      let dataDescription = document.data() // your json response or value
      var leadData = dataDescription
      _ = leadData.removeValue(forKey: "serverTimeStamp") // remove  FIRTimestamp
     let requestData = try! JSONSerialization.data(withJSONObject: leadData, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData?
     let results = try JSONDecoder().decode(leadDocument.self, from: requestData! as Data)

将FIRTimestamp或隐蔽为JSON

 let db = Firestore.firestore()
 let settings = db.settings
 settings.areTimestampsInSnapshotsEnabled = true
 db.settings = settings
 let timestamp: Timestamp = document.get("serverTimeStamp") as! Timestamp
 let date: Date = timestamp.dateValue()
print(date)

答案 1 :(得分:0)

如果您要序列化FIRTimestamp的内容,则应该:

  1. 使用dateValue将其转换为NSDate,然后对其进行序列化
  2. 使用链接的方法将其转换为秒(如果需要,还可转换为nanoseconds

反序列化这些值时,可以使用其构造函数之一将它们转换回FIRTimestamp