So I'm whipping up something quick and dirty for a work project. I've got a C# class that is all string types, nothing fancy, and once the item is created it gets serialized with the new System.Text.Json stuff and then attempts to POST to a web server. If that POST fails I write the data to a log file that has today's date as the name. If the file exists I need to append to the file.
All pretty straight forward right?
If today's file does not exist writing the object out is easy:
In this case "rpt" is a single item of my class, this writes the JSON file correctly. I have also tried serializing a List<> of my class and the serializer builds the output correctly. All good so far!
Now my issue comes when dealing with appending objects to my file. Because I need valid JSON I can't just add the single item to the existing text file because that isn't valid.
The code I came up with for appending the items is as follows:
This works great if the JSON file it reads contains an array (2+ items) and correctly appends the new item.
However if this tries to read a file with a single item in it, it blows up with this:
I will admit I haven't dabbled in this stuff in a while and I might be missing something completely obvious. Any ideas on how to do this perhaps a better way? Why isn't the deserializer returning a list of 1?
All pretty straight forward right?
If today's file does not exist writing the object out is easy:
Code:
File.WriteAllText(path, JsonSerializer.Serialize(rpt, options), Encoding.UTF8);
In this case "rpt" is a single item of my class, this writes the JSON file correctly. I have also tried serializing a List<> of my class and the serializer builds the output correctly. All good so far!
Now my issue comes when dealing with appending objects to my file. Because I need valid JSON I can't just add the single item to the existing text file because that isn't valid.
The code I came up with for appending the items is as follows:
Code:
List<Report> reports = JsonSerializer.Deserialize<List<Report>>(File.ReadAllText(path, Encoding.UTF8));
reports.Add(rpt);
File.WriteAllText(path, JsonSerializer.Serialize(reports, options), Encoding.UTF8);
This works great if the JSON file it reads contains an array (2+ items) and correctly appends the new item.
However if this tries to read a file with a single item in it, it blows up with this:
System.Text.Json.JsonException: 'The JSON value could not be converted to System.Collections.Generic.List`1[TelemetryCollector.Report]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'
I will admit I haven't dabbled in this stuff in a while and I might be missing something completely obvious. Any ideas on how to do this perhaps a better way? Why isn't the deserializer returning a list of 1?