我正在编写一个WPF应用程序,我将数据保存在JSON文件中。 问题是我在我的对象中有一个ObservableCollection来序列化,每次我写这个文件时它都没有写ObservableCollection!(其他变量写的都是正确的)我检查了它的集合并且它不是null。
class VarGlob
{
private int demandeCount;
private int etatDemandeObj;
private ObservableCollection<Chapitre> dataContextObj;
private static ObservableCollection<Chapitre> dataContext;
private static int numBonDeCom;
public int DemandeCount { get => demandeCount; set => demandeCount = value; }
public int EtatDemandeObj { get => etatDemandeObj; set => etatDemandeObj = value; }
public static ObservableCollection<Chapitre> DataContext { get => dataContext; set => dataContext = value; }
internal ObservableCollection<Chapitre> DataContextObj { get => dataContextObj; set => dataContextObj = value; }
public VarGlob()
{
DemandeCount = Demande.DemandeCount;
EtatDemandeObj = Demande.EtatDemande;
DataContextObj = DataContext;
}
public static void initVarGlob()
{
using (StreamReader file = File.OpenText(@"./VarGlob.json"))
{
JsonSerializer serializer = new JsonSerializer();
VarGlob varGlob = (VarGlob) serializer.Deserialize(file, typeof(VarGlob));
Demande.DemandeCount = varGlob.DemandeCount;
Demande.EtatDemande = varGlob.EtatDemandeObj;
if (varGlob.EtatDemandeObj == 0)
{
VarGlob.DataContext = Chapitre.GetChapitres("FirstDB");
}else
VarGlob.DataContext = varGlob.DataContextObj;
}
}
public static void saveVarGlob()
{
File.WriteAllText(@".\VarGlob.json", JsonConvert.SerializeObject(new VarGlob()));
}
这是文件内容:
{"DemandeCount":0,"EtatDemandeObj":0}
编辑:我忘了提到当我将ObservableCollection单独写入另一个文件时,它的工作原理是代码:
File.WriteAllText(@"./MainDataContext"+ ".json", JsonConvert.SerializeObject(DataContext));
感谢您的帮助!