Stefano Ston
Stefano Ston

Reputation: 91

Json array exception

I create a Json file and insert some objects of my class inside it, like this:

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));                    
}

Then when I try to read the file and deserialize the json I get this exception. how could i solve?

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: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.ObjectModel.ObservableCollection`1[MotiVApp.NotePage+Note]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'FraseGiorno', line 1, position 15.'

I don't understand why the exception refers to the 'FraseGiorno' property

Upvotes: 1

Views: 180

Answers (1)

David L
David L

Reputation: 33833

You are serializing an object into the file, but deserializing into a collection.

If you absolutely must use an ObservableCollection, separate the initialization and deserialization steps:

var note = JsonConvert.DeserializeObject<Note>(File.ReadAllText(NotesFile));
listNode.Add(note);
CollectionNote.ItemsSource = listNote;

Upvotes: 1

Related Questions