krky
krky

Reputation: 1

Adding a list to JSON file

I am try to create some sort of register for a gas station. Its simple enough where i just keep some files with worker info, gas info, and receipts. However i am having trouble with storing/then reading receipt data in my receipt JSON file. Here is my code for storing data to a file:

var newReceipt = new List<Receipts>
       {
                new Receipts
                {
                //...
                //data
                //...
                }
       };
var nReceipt = JsonConvert.SerializeObject(newReceipt);
File.AppendAllText(receiptFile, nReceipt);

Using this code my file looks like this after 2 runs of it

[
  {
    "pricePerL": 10.22,
    "ID": "NH1164DTDE",
    "amount": 10.0,
    "tax": 25.5500011,
    "totalPrice": 102.200005,
    "time": "01.20.2023 13:12",
    "sort": "beznin",
    "typeOfPayment": "card",
    "employee": "Denis"
  }
][
  {
    "ID": "300FIMTU7U",
    "sort": "disel",
    "employee": "Denis",
    "amount": 150.0,
    "pricePerL": 13.24,
    "tax": 496.5,
    "totalPrice": 1986.0,
    "typeOfPayment": "cash",
    "time": "01.20.2023 13:19"
  }
]

I have trouble reading this using my other function due to square brackets between. Other function simply uses foreach to go through the file and writes out some info about receipts and i found it working when there are no square brackets between two receipts.

I have tried a bunch of way to record data to that JSON file but there are always those square brackets there. My other function for writing out all receipts in that file returns exception: "Additional text encountered after finished reading JSON content "

My other function:

static void pregledRacuna(List<Receipts> racuniLista)
        {
            try
            {
                foreach (Receipts r in racuniLista)
                {
                  //writes out id and date
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

P.S. this is my first post here so if there is any clarification needed please do say so!

Upvotes: 0

Views: 68

Answers (1)

Serge
Serge

Reputation: 43860

you can not just append a new text to the file, you will have to read all text from the file, deserialize, add new item and write all after this

string json = File.ReadAllText(receiptFile);
var receipts= JsonConvert.DeserializeObject<List<Receipts>>(json);
receipts.Add(
                new Receipts
                {
                //...
                //data
                //...
                }
       );

json  = JsonConvert.SerializeObject(receipts);
File.WriteAllText(receiptFile, json);

Upvotes: 2

Related Questions