Files
sessionzero-cs/SzCore/SzParser.cs
2026-01-26 10:24:16 -06:00

67 lines
1.7 KiB
C#

using System.Text.Json;
using SzCore.DataObjects;
namespace SzCore;
public class SzParser
{
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("Dataset Serialization Error: " + e.Message);
}
}
public SzDataset? DeserializeDataset(string jsonString)
{
try
{
var result = JsonSerializer.Deserialize<SzDataset>(jsonString, _jsonOptions);
return result;
}
catch (Exception e)
{
SZ.Logger.LogError("Could not deserialize JSON to type SzDataset: " + e.Message);
return null;
}
}
public string SerializeTemplateToJson(ISzTemplate template)
{
try
{
var templateType = template.GetType();
var jsonString = JsonSerializer.Serialize(template, templateType, _jsonOptions);
return jsonString;
}
catch (Exception e)
{
throw new Exception("Template Serialization Error: " + e.Message);
}
}
public T? DeserializeTemplate<T>(string jsonString)
{
try
{
var result = JsonSerializer.Deserialize<T>(jsonString, _jsonOptions);
return result;
}
catch (Exception e)
{
SZ.Logger.LogError($"Could not deserialize JSON to type {typeof(T)}: " + e.Message);
return default;
}
}
}