From 2dd63ccba073075a54e12db97ac01e070467ad14 Mon Sep 17 00:00:00 2001 From: Tony Bark Date: Sun, 16 Mar 2025 12:58:46 -0400 Subject: [PATCH] Fixed JSON error - If JSON file doesn't exist, write one that does and add brackets. - Trim any white space in the values --- Config.cs | 2 +- Program.cs | 29 +++++++++++++++++------------ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/Config.cs b/Config.cs index 933c122..b5c236f 100644 --- a/Config.cs +++ b/Config.cs @@ -10,7 +10,7 @@ public class Config /// /// Gets or sets the name of the schedule file. /// - public string File { get; set; } = "schedule.txt"; + public string File { get; set; } = "schedule.json"; /// /// Gets or sets the directory path where the schedule file is stored. diff --git a/Program.cs b/Program.cs index 2fdbc2c..631fc3d 100644 --- a/Program.cs +++ b/Program.cs @@ -146,7 +146,7 @@ string NewTopic(List topics) /// the directory, filename, and list of topics based on /// a configuration file if available. /// -void ExportSchedule(List storeSchedule) +void ExportSchedule(List storeTimes) { // App directory is used for config file var appDir = AppDomain.CurrentDomain.BaseDirectory; @@ -160,6 +160,7 @@ void ExportSchedule(List storeSchedule) var outputFile = config.File; var filePath = Path.Combine(outputDir, outputFile!); var chosenTopic = ""; + var times = new List(); // If the config file exists, read from that but don't assume anything is filled @@ -188,31 +189,35 @@ void ExportSchedule(List storeSchedule) filePath = Path.Combine(outputDir, outputFile!); } + if (!File.Exists(filePath)) + File.WriteAllText(filePath, "[]"); + + foreach (var time in storeTimes) + times.Add(time.Trim()); + // Set new topic topics = config.Topics.ToList(); chosenTopic = NewTopic(topics); // Write to file. - JsonWriterOptions options = new() - { - Indented = true - }; + var jsonContent = File.ReadAllText(filePath); + var jsonList = string.IsNullOrWhiteSpace(jsonContent) ? new List() + : JsonSerializer.Deserialize>(jsonContent) ?? new List(); - var jsonList = JsonSerializer.Deserialize>(filePath) - ?? new List(); jsonList.Add(new Schedule() { - Topic = chosenTopic, - Times = storeSchedule, + Topic = chosenTopic.Trim(), + Times = times, }); + var jsonString = JsonSerializer.Serialize(jsonList); - Console.WriteLine(jsonString); - // File.WriteAllText(filePath, jsonString); + Console.WriteLine(jsonList); + File.WriteAllText(filePath, jsonString); Console.WriteLine($"{Environment.NewLine}Written to: {filePath}"); // Clear list from memory - storeSchedule.Clear(); + storeTimes.Clear(); } ///