Firebase数据库时间戳未序列化,出现错误{“解析值时遇到意外字符:{.路径'日期',

b5buobof  于 2022-11-17  发布在  其他
关注(0)|答案(3)|浏览(64)

我想检索firestore集合的时间戳数据,但收到错误- {“解析值时遇到意外字符:{.路径'日期',
date field data screenshot
data screenshot
样本数据集

{"Tyres":"12","sr_no":"","TruckNumber":"TS 12345","image_url":"https://firebasestorage.googleapis.com/v0/b/truck-41c31.appsp.jpg?alt=media&token=2dc86208-7f71-4e3c-876c-70a80d4822bf","date":{}}

代码

Query truckQuery = fireStoreDb.Collection("users/QRRsqyWUas/orders");
                QuerySnapshot truckQuerySnapshot = await truckQuery.GetSnapshotAsync();
                List<Truck> lstTruck = new List<Truck>();

                foreach (DocumentSnapshot documentSnapshot in truckQuerySnapshot.Documents)
                {
                    if (documentSnapshot.Exists)
                    {
                        Dictionary<string, object> city = documentSnapshot.ToDictionary();
                        string json = JsonConvert.SerializeObject(city);
                        Truck newtruck = JsonConvert.DeserializeObject<Truck>(json);
                        newtruck.TruckNumber = documentSnapshot.Id;
                        newtruck.date = documentSnapshot.CreateTime.Value.ToDateTime();
                        lstTruck.Add(newtruck);
                    }
                }

模型公共级卡车

{

        [FirestoreProperty]
        [Required]
        public string TruckNumber { get; set; }
        [FirestoreProperty]
        [Required]
        public string Tyres { get; set; }
      
        public DateTime date { get; set; }
        [FirestoreProperty]
        [Required]
        public string image_url { get; set; }
        [FirestoreProperty]
        [Required]
        public string sr_no { get; set; }
    }

firestore日期字段数据-29 June 2020 at 22:23:44 UTC+5:30

x8diyxa7

x8diyxa71#

foreach (DocumentSnapshot documentSnapshot in truckQuerySnapshot.Documents)
                {
                    if (documentSnapshot.Exists)
                    {
                        Dictionary<string, object> city = documentSnapshot.ToDictionary();
                        city["date"] = DateTime.Now.ToString();//modified here for resolve
                        string json = JsonConvert.SerializeObject(city);
                        Truck newtruck = JsonConvert.DeserializeObject<Truck>(json);
                        newtruck.Docid = documentSnapshot.Id;
                        newtruck.date = documentSnapshot.CreateTime.Value.ToDateTime();
                        lstTruck.Add(newtruck);
                    }
                }

我现在已经在serializeObject(city)之前分配了datetime,我的错误消失了。

unhi4e5o

unhi4e5o2#

我在.netcore 5中遇到相同的错误与firebase数据库

解决方案

属性变更:终止日期时间偏移
例如...“**public DateTimeOffset date { get; set; }**
并在数据库中插入日期,始终使用UTC
例如... **object.date = DateTime.UtcNow;**
我希望这对每个人都有帮助。

e0uiprwp

e0uiprwp3#

我面对这个问题,我解决了它,我不知道这是否是一个解决方案,但我会在这里分享它
同时,利用该方法将返回的Dictionary转换为Observablecollection模型

using Google.Cloud.Firestore;
FirestoreDb fdb;
private ObservableCollection<Items_Model> _result = new ObservableCollection<Items_Model>();
public ObservableCollection<Items_Model> result
{
    get { return _result; }
}
public Page_Items()
        {
            InitializeComponent();
            
            MyListView.ItemsSource = result;
            GetAllItems();
        }

物料_模型

using System;
using System.ComponentModel;
using System.Text.Json.Serialization;

namespace WPFApp1.Models
{
    public class Items_Model : INotifyPropertyChanged
    {
        private string _Name { get; set; }

        public Guid id { get; set; }
        
        public string Name
        {
            get { return _Name; }
            set { _Name = value; NotifyPropertyChanged("Name"); }
        }
        
        
    
        public string iid { get; set; }
        public string Barcode { get; set; }
        public string ImageUrl { get; set; }
        public string Section { get; set; }
        public string Notes { get; set; }
        [JsonIgnore]
        public DateTime AddDate { get; set; }
        [JsonIgnore]
        public DateTime UpdateDate { get; set; }
        public string AddBy { get; set; }
        public string UpdateBy { get; set; }
        [JsonIgnore]
        public string Key { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

这是我的解决方案

public async void GetAllItems()
    {
        try
        {
            CollectionReference customersRef = fdb.Collection("Items");
            FirestoreChangeListener listener = customersRef.Listen(snapshot =>
            {
                foreach (var change in snapshot.Changes)
                {

                    var dic = change.Document.ToDictionary();
                    
                    
                    //Here I Convert to DateTime
                    string AddD = dic["AddDate"].ToString();
                    string stringAddDate = AddD.Split(new string[] { "Timestamp: " }, StringSplitOptions.None).Last();
                    DateTime AddDate = Convert.ToDateTime(stringAddDate);

                    string UpD = dic["UpdateDate"].ToString();
                    string stringUpdateDate = UpD.Split(new string[] { "Timestamp: " }, StringSplitOptions.None).Last();
                    DateTime UpdateDate = Convert.ToDateTime(stringUpdateDate);

                    var obj = new Items_Model();
                    obj.id = Guid.Parse(dic["id"].ToString());
                    obj.iid = (dic["iid"] == null ? "" : dic["iid"].ToString());
                    obj.Name = (dic["Name"] == null ? "" : dic["Name"].ToString()) ;
                    obj.Barcode = (dic["Barcode"] == null ? "" : dic["Barcode"].ToString()) ;
                    obj.ImageUrl = (dic["ImageUrl"] == null ? "" : dic["ImageUrl"].ToString());
                    obj.Section = (dic["Section"] == null ? "" : dic["Section"].ToString()); 
                    obj.Notes = (dic["Notes"] == null ? "" : dic["Notes"].ToString()); 
                    obj.AddDate = AddDate;
                    obj.UpdateDate = UpdateDate;
                    obj.AddBy = (dic["AddBy"] == null ? "" : dic["AddBy"].ToString());
                    obj.UpdateBy = (dic["UpdateBy"] == null ? "" : dic["UpdateBy"].ToString());
                    

                    if (change.ChangeType.ToString() == "Added")
                    {
                        App.Current.Dispatcher.Invoke((Action)delegate
                        {
                            result.Add(obj);
                        });
                        
                    }
                    else if (change.ChangeType.ToString() == "Modified")
                    {
                        if (result.Where(c => c.id == obj.id).Any())
                        {
                            var item = result.Where(c => c.id == obj.id).FirstOrDefault();
                            //item = obj;

                            App.Current.Dispatcher.Invoke((Action)delegate
                            {
                                result.Insert(result.IndexOf(item), obj);
                                result.Remove(item);
                            });
                            
                        }
                    }
                    else if (change.ChangeType.ToString() == "Removed")
                    {
                        if (result.Where(c => c.id == obj.id).Any())
                        {
                            var item = result.Where(c => c.id == obj.id).FirstOrDefault();
                            App.Current.Dispatcher.Invoke((Action)delegate
                            {
                                result.Remove(item);
                            });
                            
                        }
                    }
                }

            });
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
        }
    }

相关问题