Datasets now serialize/save and deserialize/load properly. Created a test in the CLI project

This commit is contained in:
2026-01-21 22:31:18 -06:00
parent dc7ddc0c6c
commit ad2e074991
10 changed files with 169 additions and 46 deletions

View File

@@ -3,37 +3,71 @@ using SzLib.DataObjects;
namespace SzLib;
public class SzParser
public class SzParser(ISzFileManager szFileManager)
{
public readonly ISzFileManager FileManager;
private readonly JsonSerializerOptions _jsonOptions = new() { WriteIndented = true };
private JsonSerializerOptions _jsonOptions = new()
{
WriteIndented = true,
};
public SzParser(ISzFileManager szFileManager)
{
FileManager = szFileManager;
}
public (string result, SzParseError error) SerializeDatasetToJson(SzDataset dataset)
public string SerializeDatasetToJson(SzDataset dataset)
{
try
{
var jsonString = JsonSerializer.Serialize(dataset, _jsonOptions);
return (jsonString, SzParseError.None);
return jsonString;
}
catch (JsonException e)
{
return ("", SzParseError.CouldNotSerialize);
throw new Exception("Parse Error: " + e.Message);
}
}
public SzDataset? DeserializeDataset(string jsonString)
{
try
{
var result = JsonSerializer.Deserialize<SzDataset>(jsonString, _jsonOptions);
return result;
}
catch (Exception e)
{
throw new Exception("Could not deserialize JSON to type SzDataset: " + e.Message, e);
}
}
public bool SaveDataset(SzDataset dataset)
{
var datasetDir = Path.Combine(szFileManager.DataPath, "datasets", dataset.Id);
Directory.CreateDirectory(datasetDir);
try
{
var json = SerializeDatasetToJson(dataset);
File.WriteAllText(Path.Combine(datasetDir, "dataset.json"), json);
return true;
}
catch (Exception e)
{
Console.WriteLine("Error saving dataset: " + e.Message);
return false;
}
}
public SzDataset? LoadDataset(string datasetId)
{
var datasetPath = Path.Combine(szFileManager.DataPath, "datasets", datasetId, "dataset.json");
if (!File.Exists(datasetPath))
{
Console.WriteLine("Dataset not found: " + datasetId);
return null;
}
try
{
return DeserializeDataset(File.ReadAllText(datasetPath));
}
catch (Exception e)
{
Console.WriteLine($"Error loading dataset: {e.Message}");
return null;
}
}
}
public enum SzParseError
{
None,
CouldNotSerialize,
GenericError,
}