LevelOS-Core/TLL/JsonHelper.cs

72 lines
1.8 KiB
C#

using System;
using System.IO;
using System.Text.Json;
public static class JsonHelper
{
private static readonly JsonSerializerOptions _options = new JsonSerializerOptions
{
WriteIndented = true // JSON bonito
};
// 🔹 SALVAR JSON
public static void Salvar<T>(T objeto, string caminho)
{
try
{
string json = JsonSerializer.Serialize(objeto, _options);
// Garante que a pasta existe
string pasta = Path.GetDirectoryName(caminho);
if (!Directory.Exists(pasta))
Directory.CreateDirectory(pasta);
File.WriteAllText(caminho, json);
}
catch (Exception ex)
{
throw new Exception("Erro ao salvar JSON: " + ex.Message);
}
}//Salvar
public static bool SalvarBoolean<T>(T objeto, string caminho)
{
try
{
string json = JsonSerializer.Serialize(objeto, _options);
string pasta = Path.GetDirectoryName(caminho);
if (!string.IsNullOrWhiteSpace(pasta) && !Directory.Exists(pasta))
Directory.CreateDirectory(pasta);
File.WriteAllText(caminho, json);
return true;
}
catch
{
return false;
}
}
// 🔹 LER JSON
public static T Ler<T>(string caminho) where T : new()
{
try
{
if (!File.Exists(caminho))
return new T();
string json = File.ReadAllText(caminho);
if (string.IsNullOrWhiteSpace(json))
return new T();
return JsonSerializer.Deserialize<T>(json) ?? new T();
}
catch (Exception ex)
{
throw new Exception("Erro ao ler JSON: " + ex.Message);
}
}
}