Files
sessionzero-cs/SzLib/SzParser.cs

74 lines
2.0 KiB
C#

using System.Text.Json;
using SzLib.DataObjects;
namespace SzLib;
public class SzParser(ISzFileManager szFileManager)
{
private readonly JsonSerializerOptions _jsonOptions = new() { WriteIndented = true };
public string SerializeDatasetToJson(SzDataset dataset)
{
try
{
var jsonString = JsonSerializer.Serialize(dataset, _jsonOptions);
return jsonString;
}
catch (JsonException e)
{
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;
}
}
}