Elisa/Elisa.Common/Data/JSON.cs

32 lines
811 B
C#

using System.Text.Json;
namespace Elisa.Common.Data;
public static class JSON
{
public static JsonSerializerOptions serializerOptions = new() { IncludeFields = true, WriteIndented = true };
public static T Load<T>(string path, bool create = true) where T : new()
{
if (!File.Exists(path) && create)
{
T obj = new T();
Save(path, obj);
}
string text = File.ReadAllText(path);
return JsonSerializer.Deserialize<T>(text, serializerOptions) ?? new T();
}
public static void Save<T>(string path, T obj)
{
File.WriteAllText(path, JsonSerializer.Serialize(obj, serializerOptions));
}
public static string Stringify<T>(T obj)
{
return JsonSerializer.Serialize(obj, serializerOptions);
}
}