【发布时间】:2021-04-19 20:08:27
【问题描述】:
我创建了一个 Json 文件并在其中插入了我的类的一些对象,如下所示:
private async void Save_Clicked(object sender, EventArgs e)
{
Note NoteNew = new Note
{
FraseGiorno = obj1.FraseGiornaliera,
Nota = TestoNota.Text,
Data= DateTime.Today.ToString().Remove(10,9),
};
File.WriteAllText(NotesFile, JsonConvert.SerializeObject(NoteNew));
}
然后,当我尝试读取文件并反序列化 json 时,我得到了这个异常。怎么解决?
string NotesFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Note.json");
ObservableCollection<Note> listNote = new ObservableCollection<Note>();
FraseClass obj1;
public NotePage(FraseClass obj1)
{
InitializeComponent();
this.obj1 = obj1;
if (File.Exists(NotesFile))
{
listNote = JsonConvert.DeserializeObject<ObservableCollection<Note>>(File.ReadAllText(NotesFile));
CollectionNote.ItemsSource = listNote;
}
}
Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.ObjectModel.ObservableCollection`1[MotiVApp.NotePage+Note]',因为type 需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。 要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“FraseGiorno”,第 1 行,位置 15。
我不明白为什么异常指的是“FraseGiorno”属性
【问题讨论】:
-
你序列化一个对象,你想反序列化一个集合,为什么?试试
JsonConvert.DeserializeObject<Note>(File.ReadAllText(NotesFile));
标签: c# json xaml xamarin.forms