Home > Back-end >  Deserializie multiple JSON Objects from file C#
Deserializie multiple JSON Objects from file C#

Time:07-05

I'm serializing Objects as JSON String in a .txt file with the following code:

private void ReserveTable_Click(object sender, EventArgs e)
    {
        
        Reservation CreateReservation = new Reservation(textBoxFirstName.Text, textBoxSecondName.Text, dateTimePickerDate.Value.ToShortDateString(), comboBoxTable.Text, 5, textBoxPhoneNumber.Text);
        string jsonString = JsonSerializer.Serialize(CreateReservation);
        File.AppendAllText(Globals.filepath, jsonString);

    }

It creates multiple json String in that file, looking like this:

{"Firstname":"Rainer","Lastname":"Maier","Date":"07.07.2022","Table":"Tisch 8 (Au\u00DFenbereich)","NumberOfPersons":5,"Phonenumber":"4756465465"}{"Firstname":"Timo","Lastname":"Winkler","Date":"07.07.2022","Table":"Tisch 8 (Au\u00DFenbereich)","NumberOfPersons":5,"Phonenumber":"5674654"}

Then im trying to deserialize the file, to put the attributes into a table:

  private void ShowReservation_Click(object sender, EventArgs e)
    {
        string jsonString = File.ReadAllText(Globals.filepath);
        Reservation ReadReservation = JsonSerializer.Deserialize<Reservation>(jsonString)!;
        Console.WriteLine(ReadReservation);

    }

I'm not able to deserialize both objects. With the Error Code:

'{' is invalid after a single JSON value. Expected end of data.

Is there any way to deserialize the multiple Objects or to serialize it smarter? In this program you can create multiple reservations which need to be stored in a file.

CodePudding user response:

The issue is that a collection of items in JSON format is not represented by taking individual serialized items and appending them after one another (like in your output example. What you want is a collection format in JSON, which should look like this:

[{"Firstname":"Rainer","Lastname":"Maier","Date":"07.07.2022","Table":"Tisch 8 (Au\u00DFenbereich)","NumberOfPersons":5,"Phonenumber":"4756465465"},{"Firstname":"Timo","Lastname":"Winkler","Date":"07.07.2022","Table":"Tisch 8 (Au\u00DFenbereich)","NumberOfPersons":5,"Phonenumber":"5674654"}]

Notice the square brackets (indicating an array), and the commas separating each object. You can then deserialize this file using something like this:

Reservations List<ReadReservation> = JsonSerializer.Deserialize<List<Reservation>>(jsonString);

The easiest way to solve your issue instead of using append, deserialize the file contents, add an item to the list, then serialize the collection back. If performance is a concern, then a better approach would be to append using line breaks (or some delimiting value), and then use a reader to read the individual chunks and deserialize them individually one by one.

  • Related